Java Code Examples for java.awt.Graphics2D#dispose()

The following examples show how to use java.awt.Graphics2D#dispose() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Test chart drawing with an empty dataset to ensure that this special
 * case doesn't cause any exceptions.
 */
public void testDrawWithEmptyDataset() {
    boolean success = false;
    JFreeChart chart = ChartFactory.createStackedXYAreaChart("title", "x",
            "y", new DefaultTableXYDataset(), true);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setRenderer(new StackedXYAreaRenderer2());
    try {
        BufferedImage image = new BufferedImage(200 , 100,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
        g2.dispose();
        success = true;
    }
    catch (Exception e) {
        success = false;
    }
    assertTrue(success);
}
 
Example 2
protected BufferedImage createTestImage(int numColors) {

        IndexColorModel icm = createTestICM(numColors);
        int w = numColors * 10;
        int h = 20;

        BufferedImage img = new BufferedImage(w, h,
                BufferedImage.TYPE_BYTE_INDEXED, icm);

        Graphics2D g = img.createGraphics();
        for (int i = 0; i < numColors; i++) {
            int rgb = icm.getRGB(i);
            //System.out.printf("pixel %d, rgb %x\n", i, rgb);
            g.setColor(new Color(rgb));
            g.fillRect(i * 10, 0, w - i * 10, h);
        }
        g.dispose();

       return img;
    }
 
Example 3
public VolatileImage accelerateImage(BufferedImage bi) {
    VolatileImage testVI = f.createVolatileImage(TEST_W, TEST_H);
    do {
        if (testVI.validate(f.getGraphicsConfiguration()) ==
            VolatileImage.IMAGE_INCOMPATIBLE)
        {
            testVI = f.createVolatileImage(TEST_W, TEST_H);
        }
        Graphics2D g = testVI.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.setColor(Color.green);
        g.fillRect(0, 0, TEST_W, TEST_H);

        g.drawImage(bi, 0, 0, null);
        g.drawImage(bi, 0, 0, null);
        g.drawImage(bi, 0, 0, null);
        g.dispose();
    } while (testVI.contentsLost());

    return testVI;
}
 
Example 4
private static BufferedImage createTestImage() {
    int w = 1024;
    int h = 768;

    BufferedImage img = new
        BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    Color[] colors = { Color.red, Color.green, Color.blue };
    float[] dist = {0.0f, 0.5f, 1.0f };
    Point2D center = new Point2D.Float(0.5f * w, 0.5f * h);

    RadialGradientPaint p =
        new RadialGradientPaint(center, 0.5f * w, dist, colors);
    g.setPaint(p);
    g.fillRect(0, 0, w, h);
    g.dispose();

    return img;
}
 
Example 5
Source Project: pentaho-kettle   File: SwingDirectGC.java    License: Apache License 2.0 6 votes vote down vote up
private void drawImage( SwingUniversalImage img, int locationX, int locationY, int imageSize ) {
  if ( isDrawingPixelatedImages() && img.isBitmap() ) {
    BufferedImage bi = new BufferedImage( imageSize, imageSize, BufferedImage.TYPE_INT_ARGB );
    Graphics2D g2 = (Graphics2D) bi.getGraphics();
    g2.setColor( Color.WHITE );
    g2.fillRect( 0, 0, imageSize, imageSize );
    g2.drawImage( img.getAsBitmapForSize( imageSize, imageSize ), 0, 0, observer );
    g2.dispose();

    for ( int x = 0; x < bi.getWidth( observer ); x++ ) {
      for ( int y = 0; y < bi.getHeight( observer ); y++ ) {
        int rgb = bi.getRGB( x, y );
        gc.setColor( new Color( rgb ) );
        gc.setStroke( new BasicStroke( 1.0f ) );
        gc.drawLine( locationX + xOffset + x, locationY + yOffset + y, locationX + xOffset + x, locationY
          + yOffset + y );
      }
    }
  } else {
    gc.setBackground( Color.white );
    gc.clearRect( locationX, locationY, imageSize, imageSize );
    img.drawToGraphics( gc, locationX, locationY, imageSize, imageSize );
  }
}
 
Example 6
@Override
public void flip(final LWComponentPeer<?, ?> peer, final Image backBuffer,
                 final int x1, final int y1, final int x2, final int y2,
                 final BufferCapabilities.FlipContents flipAction) {
    final Graphics g = peer.getGraphics();
    try {
        g.drawImage(backBuffer, x1, y1, x2, y2, x1, y1, x2, y2, null);
    } finally {
        g.dispose();
    }
    if (flipAction == BufferCapabilities.FlipContents.BACKGROUND) {
        final Graphics2D bg = (Graphics2D) backBuffer.getGraphics();
        try {
            bg.setBackground(peer.getBackground());
            bg.clearRect(0, 0, backBuffer.getWidth(null),
                         backBuffer.getHeight(null));
        } finally {
            bg.dispose();
        }
    }
}
 
Example 7
private static BufferedImage createTestImage() {
    int w = 1024;
    int h = 768;

    BufferedImage img = new
        BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    Color[] colors = { Color.red, Color.green, Color.blue };
    float[] dist = {0.0f, 0.5f, 1.0f };
    Point2D center = new Point2D.Float(0.5f * w, 0.5f * h);

    RadialGradientPaint p =
        new RadialGradientPaint(center, 0.5f * w, dist, colors);
    g.setPaint(p);
    g.fillRect(0, 0, w, h);
    g.dispose();

    return img;
}
 
Example 8
/**
 * Draws standard JMenuBar.
 */
private BufferedImage step1(final JMenuBar menubar) {
    final BufferedImage bi1 = new BufferedImage(W, H, TYPE_INT_ARGB_PRE);
    final Graphics2D g2d = bi1.createGraphics();
    g2d.scale(2, 2);
    g2d.setColor(Color.RED);
    g2d.fillRect(0, 0, W, H);
    menubar.paintAll(g2d);
    g2d.dispose();
    return bi1;
}
 
Example 9
Source Project: FlatLaf   File: FlatLineBorder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void paintBorder( Component c, Graphics g, int x, int y, int width, int height ) {
	Graphics2D g2 = (Graphics2D) g.create();
	try {
		FlatUIUtils.setRenderingHints( g2 );
		g2.setColor( lineColor );
		FlatUIUtils.paintComponentBorder( g2, x, y, width, height, 0f, scale( lineThickness ), 0f );
	} finally {
		g2.dispose();
	}
}
 
Example 10
/**
 * Clear a transparent image to 100% transparent
 *
 * @param img The image to clear
 */
static void clearImage(BufferedImage img) {
    Graphics2D g2 = img.createGraphics();
    g2.setComposite(AlphaComposite.Clear);
    g2.fillRect(0, 0, img.getWidth(), img.getHeight());
    g2.dispose();
}
 
Example 11
private static void draw(final BufferedImage from,final Image to) {
    final Graphics2D g2d = (Graphics2D) to.getGraphics();
    g2d.setComposite(AlphaComposite.Src);
    g2d.setColor(Color.ORANGE);
    g2d.fillRect(0, 0, to.getWidth(null), to.getHeight(null));
    g2d.rotate(Math.toRadians(45));
    g2d.clip(new Rectangle(41, 42, 43, 44));
    g2d.drawImage(from, 50, 50, Color.blue, null);
    g2d.dispose();
}
 
Example 12
public static void main(final String[] args) throws IOException {
    for (int  point = 5; point < 11; ++point) {
        Graphics2D g2d = bi.createGraphics();
        g2d.setFont(new Font(Font.DIALOG, Font.PLAIN, point));
        g2d.scale(scale, scale);
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.green);
        g2d.drawString(TEXT, 0, 20);
        int length = g2d.getFontMetrics().stringWidth(TEXT);
        if (length < 0) {
            throw new RuntimeException("Negative length");
        }
        for (int i = (length + 1) * scale; i < width; ++i) {
            for (int j = 0; j < height; ++j) {
                if (bi.getRGB(i, j) != Color.white.getRGB()) {
                    g2d.drawLine(length, 0, length, height);
                    ImageIO.write(bi, "png", new File("image.png"));
                    System.out.println("length = " + length);
                    System.err.println("Wrong color at x=" + i + ",y=" + j);
                    System.err.println("Color is:" + new Color(bi.getRGB(i,
                                                                         j)));
                    throw new RuntimeException("Test failed.");
                }
            }
        }
        g2d.dispose();
    }
}
 
Example 13
private void paintGradient(Graphics g, int cornerRadius) {
	final Graphics2D copy = (Graphics2D) g.create();
	copy.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	final Shape clip = g.getClip();
	GradientPaint mask = new GradientPaint(0, 0, fStartColor, 0, clip.getBounds().height, fEndColor);
	copy.setPaint(mask);
	
	if(cornerRadius == 0) {
		copy.fill(clip);
	} else {
		copy.fill(new RoundRectangle2D.Double(0, 0, clip.getBounds().getWidth(), clip.getBounds().getHeight(), cornerRadius, cornerRadius));
	}
	
	copy.dispose();
}
 
Example 14
Source Project: jeewx   File: RandCodeImageServlet.java    License: Apache License 2.0 4 votes vote down vote up
@Override
	public void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		// 设置页面不缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// response.setContentType("image/png");

		// 在内存中创建图象
		final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		// 获取图形上下文
		final Graphics2D graphics = (Graphics2D) image.getGraphics();

		// 设定背景颜色
		graphics.setColor(Color.WHITE); // ---1
		graphics.fillRect(0, 0, width, height);
		// 设定边框颜色
//		graphics.setColor(getRandColor(100, 200)); // ---2
		graphics.drawRect(0, 0, width - 1, height - 1);

        final Random random = new Random();
		// 随机产生干扰线,使图象中的认证码不易被其它程序探测到
		for (int i = 0; i < count; i++) {
			graphics.setColor(getRandColor(150, 200)); // ---3

			final int x = random.nextInt(width - lineWidth - 1) + 1; // 保证画在边框之内
			final int y = random.nextInt(height - lineWidth - 1) + 1;
			final int xl = random.nextInt(lineWidth);
			final int yl = random.nextInt(lineWidth);
			graphics.drawLine(x, y, x + xl, y + yl);
		}

		// 取随机产生的认证码(4位数字)
		final String resultCode = exctractRandCode();
		for (int i = 0; i < resultCode.length(); i++) {
			// 将认证码显示到图象中,调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
			// graphics.setColor(new Color(20 + random.nextInt(130), 20 + random
			// .nextInt(130), 20 + random.nextInt(130)));

            // 设置字体颜色
			graphics.setColor(Color.BLACK);
            // 设置字体样式
//			graphics.setFont(new Font("Arial Black", Font.ITALIC, 18));
            graphics.setFont(new Font("Times New Roman", Font.BOLD, 24));
            // 设置字符,字符间距,上边距
			graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
		}

		// 将认证码存入SESSION
		request.getSession().setAttribute(SESSION_KEY_OF_RAND_CODE, resultCode);
		// 图象生效
		graphics.dispose();

		// 输出图象到页面
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}
 
Example 15
/**
 * Creates a label image.
 * @param label the label string.
 * @param font the font to use.
 * @param fontRenderContext the font render context to use.
 * @param labelColor the color of the label.
 * @param labelOutlineColor the color of the outline of the label.
 * @return buffered image of label.
 */
private BufferedImage createLabelImage(
	String label, Font font, FontRenderContext fontRenderContext, Color labelColor,
	Color labelOutlineColor) {

	// Determine bounds.
	TextLayout textLayout1 = new TextLayout(label, font, fontRenderContext);
	Rectangle2D bounds1 = textLayout1.getBounds();

	// Get label shape.
	Shape labelShape = textLayout1.getOutline(null);

	// Create buffered image for label.
	int width = (int) (bounds1.getWidth() + bounds1.getX()) + 4;
	int height = (int) (bounds1.getHeight()) + 4;
	BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

	// Get graphics context from buffered image.
	Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	g2d.translate(2D - bounds1.getX(), 2D - bounds1.getY());

	// Draw label outline.
	Stroke saveStroke = g2d.getStroke();
	g2d.setColor(labelOutlineColor);
	g2d.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

	// Draw outline
	g2d.draw(labelShape);

	// Restore stroke
	g2d.setStroke(saveStroke);
	
	g2d.setColor(labelColor);
	// Fill label
	g2d.fill(labelShape);

	// Dispose of image graphics context.
	g2d.dispose();

	return bufferedImage;
}
 
Example 16
public ReadAbortTest(String format) throws Exception {
    try {
        System.out.println("Test for format " + format);
        bimg = new BufferedImage(width, heght,
                BufferedImage.TYPE_INT_RGB);

        Graphics2D g = bimg.createGraphics();
        g.setColor(srccolor);
        g.fillRect(0, 0, width, heght);
        g.dispose();

        file = File.createTempFile("src_", "." + format, new File("."));
        ImageIO.write(bimg, format, file);
        ImageInputStream iis = ImageIO.createImageInputStream(file);

        Iterator iter = ImageIO.getImageReaders(iis);
        while (iter.hasNext()) {
            reader = (ImageReader) iter.next();
            break;
        }
        reader.setInput(iis);
        reader.addIIOReadProgressListener(this);

        // Abort reading in IIOReadProgressListener.imageStarted().
        startAbort = true;
        bimg = reader.read(0);
        startAbort = false;

        // Abort reading in IIOReadProgressListener.imageProgress().
        progressAbort = true;
        bimg = reader.read(0);
        progressAbort = false;

        iis.close();
        /*
         * All abort requests from imageStarted,imageProgress and
         * imageComplete from IIOReadProgressListener should be reached
         * otherwise throw RuntimeException.
         */
        if (!(startAborted
                && progressAborted)) {
            throw new RuntimeException("All IIOReadProgressListener abort"
                    + " requests are not processed for format "
                    + format);
        }
    } catch (Exception e) {
        throw e;
    } finally {
        Files.delete(file.toPath());
    }
}
 
Example 17
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D)g.create();

    int w = getWidth();
    int h = getHeight();
    g2d.setColor(Color.black);
    g2d.fillRect(0, 0, w, h);

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                         antialiasHint);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING,
                         renderHint);

    g2d.transform(transform);
    g2d.setPaint(paint);

    switch (shapeType) {
    default:
    case RECT:
        g2d.fillRect(0, 0, w, h);
        break;

    case ELLIPSE:
        g2d.fillOval(0, 0, w, h);
        break;

    case MULTIPLE:
        g2d.fillRect(0, 0, w/2, h/2);
        g2d.fillOval(w/2, 0, w/2, h/2);
        g2d.drawOval(0, h/2, w/2, h/2);
        g2d.drawLine(0, h/2, w/2, h);
        g2d.drawLine(0, h, w/2, h/2);
        Polygon p = new Polygon();
        p.addPoint(w/2, h);
        p.addPoint(w, h);
        p.addPoint(3*w/4, h/2);
        g2d.fillPolygon(p);
        break;
    }

    switch (paintType) {
    default:
    case BASIC:
    case LINEAR:
        g2d.setColor(Color.white);
        g2d.fillRect(startX-1, startY-1, 2, 2);
        g2d.drawString("1", startX, startY + 12);
        g2d.fillRect(endX-1, endY-1, 2, 2);
        g2d.drawString("2", endX, endY + 12);
        break;

    case RADIAL:
        g2d.setColor(Color.white);
        g2d.fillRect(ctrX-1, ctrY-1, 2, 2);
        g2d.drawString("C", ctrX, ctrY + 12);
        g2d.fillRect(focusX-1, focusY-1, 2, 2);
        g2d.drawString("F", focusX, focusY + 12);
        break;
    }

    g2d.dispose();
}
 
Example 18
public void showZoomed() {
    GlyphVector gv;
    Font backup = testFont;
    Point canvasLoc = this.getLocationOnScreen();

    /// Calculate the zoom area's location and size...
    int dialogOffsetX = (int) ( gridWidth * ( ZOOM - 1 ) / 2 );
    int dialogOffsetY = (int) ( gridHeight * ( ZOOM - 1 ) / 2 );
    int zoomAreaX =
      mouseOverCharX * gridWidth + canvasInset_X - dialogOffsetX;
    int zoomAreaY =
      mouseOverCharY * gridHeight + canvasInset_Y - dialogOffsetY;
    int zoomAreaWidth = (int) ( gridWidth * ZOOM );
    int zoomAreaHeight = (int) ( gridHeight * ZOOM );

    /// Position and set size of zoom window as needed
    zoomWindow.setLocation( canvasLoc.x + zoomAreaX, canvasLoc.y + zoomAreaY );
    if ( !nowZooming ) {
        if ( zoomWindow.getWarningString() != null )
          /// If this is not opened as a "secure" window,
          /// it has a banner below the zoom dialog which makes it look really BAD
          /// So enlarge it by a bit
          zoomWindow.setSize( zoomAreaWidth + 1, zoomAreaHeight + 20 );
        else
          zoomWindow.setSize( zoomAreaWidth + 1, zoomAreaHeight + 1 );
    }

    /// Prepare zoomed image
    zoomImage =
      (BufferedImage) zoomWindow.createImage( zoomAreaWidth + 1,
                                              zoomAreaHeight + 1 );
    Graphics2D g2 = (Graphics2D) zoomImage.getGraphics();
    testFont = testFont.deriveFont( fontSize * ZOOM );
    setParams( g2 );
    g2.setColor( Color.white );
    g2.fillRect( 0, 0, zoomAreaWidth, zoomAreaHeight );
    g2.setColor( Color.black );
    g2.drawRect( 0, 0, zoomAreaWidth, zoomAreaHeight );
    modeSpecificDrawChar( g2, currMouseOverChar,
                          zoomAreaWidth / 2, (int) ( maxAscent * ZOOM ));
    g2.dispose();
    if ( !nowZooming )
      zoomWindow.show();
    /// This is sort of redundant... since there is a paint function
    /// inside zoomWindow definition that does the drawImage.
    /// (I should be able to call just repaint() here)
    /// However, for some reason, that paint function fails to respond
    /// from second time and on; So I have to force the paint here...
    zoomWindow.getGraphics().drawImage( zoomImage, 0, 0, this );

    nowZooming = true;
    prevZoomChar = currMouseOverChar;
    testFont = backup;

    // Windows does not repaint correctly, after
    // a zoom. Thus, we need to force the canvas
    // to repaint, but only once. After the first repaint,
    // everything stabilizes. [ABP]
    if ( firstTime() ) {
        refresh();
    }
}
 
Example 19
@Override
protected byte[] imageToPlatformBytes(Image image, long format)
        throws IOException {
    String mimeType = null;
    if (format == CF_PNG) {
        mimeType = "image/png";
    } else if (format == CF_JFIF) {
        mimeType = "image/jpeg";
    }
    if (mimeType != null) {
        return imageToStandardBytes(image, mimeType);
    }

    int width = 0;
    int height = 0;

    if (image instanceof ToolkitImage) {
        ImageRepresentation ir = ((ToolkitImage)image).getImageRep();
        ir.reconstruct(ImageObserver.ALLBITS);
        width = ir.getWidth();
        height = ir.getHeight();
    } else {
        width = image.getWidth(null);
        height = image.getHeight(null);
    }

    // Fix for 4919639.
    // Some Windows native applications (e.g. clipbrd.exe) do not handle
    // 32-bpp DIBs correctly.
    // As a workaround we switched to 24-bpp DIBs.
    // MSDN prescribes that the bitmap array for a 24-bpp should consist of
    // 3-byte triplets representing blue, green and red components of a
    // pixel respectively. Additionally each scan line must be padded with
    // zeroes to end on a LONG data-type boundary. LONG is always 32-bit.
    // We render the given Image to a BufferedImage of type TYPE_3BYTE_BGR
    // with non-default scanline stride and pass the resulting data buffer
    // to the native code to fill the BITMAPINFO structure.
    int mod = (width * 3) % 4;
    int pad = mod > 0 ? 4 - mod : 0;

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    int[] nBits = {8, 8, 8};
    int[] bOffs = {2, 1, 0};
    ColorModel colorModel =
            new ComponentColorModel(cs, nBits, false, false,
                    Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    WritableRaster raster =
            Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, width, height,
                    width * 3 + pad, 3, bOffs, null);

    BufferedImage bimage = new BufferedImage(colorModel, raster, false, null);

    // Some Windows native applications (e.g. clipbrd.exe) do not understand
    // top-down DIBs.
    // So we flip the image vertically and create a bottom-up DIB.
    AffineTransform imageFlipTransform =
            new AffineTransform(1, 0, 0, -1, 0, height);

    Graphics2D g2d = bimage.createGraphics();

    try {
        g2d.drawImage(image, imageFlipTransform, null);
    } finally {
        g2d.dispose();
    }

    DataBufferByte buffer = (DataBufferByte)raster.getDataBuffer();

    byte[] imageData = buffer.getData();
    return imageDataToPlatformImageBytes(imageData, width, height, format);
}
 
Example 20
Source Project: RipplePower   File: GraphicsUtils.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * copy指定图像到目标图形中
 * 
 * @param target
 * @param source
 * @return
 */
public static BufferedImage copy(BufferedImage target, Image source) {
	Graphics2D g = target.createGraphics();
	g.drawImage(source, 0, 0, null);
	g.dispose();
	return target;
}