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

The following examples show how to use java.awt.Graphics2D#drawImage() . 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
Source Project: Spade   File: MergeLayer.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void apply(Document doc)
{
	this.parent = layer.getParentLayer();
	this.index = parent.removeLayer(layer);
	doc.reconstructFlatmap();
	doc.setCurrent(parent);
	
	BufferedImage image = new BufferedImage(doc.getWidth(), doc.getHeight(), BufferedImage.TYPE_INT_ARGB);
	BlendMode mode = layer.getBlendMode();
	{
		Graphics2D g = image.createGraphics();
		g.drawImage(parent.getBufferedImage(), 0, 0, null);
		g.setComposite(mode);
		g.drawImage(layer.getBufferedImage(), 0, 0, null);
		g.dispose();
	}
	int[] buffer = RawImage.fromBufferedImage(image).borrowBuffer();
	parent.addChangeSilent(new SetImageChange(buffer));
}
 
Example 2
private static void showFrame(final TransformedPaintTest t) {
    JFrame f = new JFrame("TransformedPaintTest");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final BufferedImage bi =
        new BufferedImage(R_WIDTH, R_HEIGHT, BufferedImage.TYPE_INT_RGB);
    JPanel p = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            t.render(g2d, R_WIDTH, R_HEIGHT);
            t.render(bi.createGraphics(), R_WIDTH, R_HEIGHT);
            g2d.drawImage(bi, R_WIDTH + 5, 0, null);

            g.setColor(Color.black);
            g.drawString("Rendered to Back Buffer", 10, 20);
            g.drawString("Rendered to BufferedImage", R_WIDTH + 15, 20);
        }
    };
    p.setPreferredSize(new Dimension(2 * R_WIDTH + 5, R_HEIGHT));
    f.add(p);
    f.pack();
    f.setVisible(true);
}
 
Example 3
private static int[] moveRGB(int width, int height, int[] rgb, double deltaX, double deltaY, Color fill) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    setRGB(img, width, height, rgb);
    BufferedImage retImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) retImg.getGraphics();
    g.setPaint(fill);
    g.fillRect(0, 0, width, height);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setTransform(AffineTransform.getTranslateInstance(deltaX, deltaY));
    g.setComposite(AlphaComposite.Src);
    g.drawImage(img, 0, 0, null);
    return getRGB(retImg);
}
 
Example 4
Source Project: pumpernickel   File: ScalingDemo.java    License: MIT License 6 votes vote down vote up
@Override
public BufferedImage call() throws Exception {
	BufferedImage bi = new BufferedImage(80, 60,
			BufferedImage.TYPE_INT_RGB);
	Graphics2D g = bi.createGraphics();
	g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);
	g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING,
			RenderingHints.VALUE_COLOR_RENDER_QUALITY);
	g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
			RenderingHints.VALUE_INTERPOLATION_BICUBIC);
	g.setRenderingHint(RenderingHints.KEY_RENDERING,
			RenderingHints.VALUE_RENDER_QUALITY);
	g.transform(TransformUtils.createAffineTransform(new Dimension(
			sampleImage.getWidth(), sampleImage.getHeight()),
			new Dimension(bi.getWidth(), bi.getHeight())));
	g.drawImage(sampleImage, 0, 0, null);
	g.dispose();
	return bi;
}
 
Example 5
private static void checkResults(Image image) {
    BufferedImage buf = new BufferedImage(w, h,
                                          BufferedImage.TYPE_INT_RGB);
    Graphics2D g = buf.createGraphics();
    g.setColor(Color.pink);
    g.fillRect(0, 0, w, h);

    g.drawImage(image, 0, 0, null);

    g.dispose();

    int rgb = buf.getRGB(w/2, h/2);

    System.out.printf("Result color: %x\n", rgb);

    /* Buffered image should be the same as the last frame
     * of animated sequence (which is filled with blue).
     * Any other color indicates the problem.
     */
    if (rgb != 0xff0000ff) {
        throw new RuntimeException("Test FAILED!");
    }

    System.out.println("Test PASSED.");
}
 
Example 6
Source Project: MyBox   File: ImageScope.java    License: Apache License 2.0 5 votes vote down vote up
public static BufferedImage indicateEllipse(BufferedImage source,
        Color color, int lineWidth, DoubleEllipse ellipse) {
    try {
        if (!ellipse.isValid()) {
            return source;
        }
        int width = source.getWidth();
        int height = source.getHeight();
        int imageType = source.getType();
        if (imageType == BufferedImage.TYPE_CUSTOM) {
            imageType = BufferedImage.TYPE_INT_ARGB;
        }
        BufferedImage target = new BufferedImage(width, height, imageType);
        Graphics2D g = target.createGraphics();
        g.drawImage(source, 0, 0, width, height, null);
        AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
        g.setComposite(ac);
        g.setColor(color);
        BasicStroke stroke = new BasicStroke(lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                1f, new float[]{lineWidth, lineWidth}, 0f);
        g.setStroke(stroke);
        DoubleRectangle rect = ellipse.getRectangle();
        g.drawOval((int) Math.round(rect.getSmallX()), (int) Math.round(rect.getSmallY()),
                (int) Math.round(rect.getWidth()), (int) Math.round(rect.getHeight()));
        g.dispose();
        return target;
    } catch (Exception e) {
        logger.error(e.toString());
        return source;
    }
}
 
Example 7
Source Project: pumpernickel   File: AbstractSearchHighlight.java    License: MIT License 5 votes vote down vote up
@Override
protected void paintComponent(Graphics g) {
	Graphics2D g2 = (Graphics2D) g;

	Rectangle clipping = getClipping(highlightInfo.jc, this);
	if (clipping.width == 0 || clipping.height == 0)
		return;

	g.clipRect(clipping.x, clipping.y, clipping.width, clipping.height);

	Point2D absCenter = SwingUtilities.convertPoint(highlightInfo.jc,
			center.x, center.y, this);
	g2.translate(absCenter.getX(), absCenter.getY());
	AffineTransform transform = (AffineTransform) getClientProperty(
			"transform");
	if (transform != null)
		g2.transform(transform);
	g2.translate(-imageCenter.x, -imageCenter.y);
	g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);
	g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
			RenderingHints.VALUE_INTERPOLATION_BILINEAR);

	Number opacity = (Number) getClientProperty("opacity");
	if (opacity != null) {
		g2.setComposite(AlphaComposite.getInstance(
				AlphaComposite.SRC_OVER, opacity.floatValue()));
	}

	g2.drawImage(image, 0, 0, null);
}
 
Example 8
/**
 * Paints an arrow in a given direction (from 0 to 2*pi).
 * @param g
 * @param direction 
 */
protected void paintArrow(Graphics g, double direction)
{        
    Graphics2D g2d = (Graphics2D)g;
    int size = (this.getWidth() > this.getHeight()) ? this.getHeight() : this.getWidth();
    
    // Arrow.
    BufferedImage image = this.getImageArrow();
    int imageWidth = image.getWidth();
    int imageHeight = image.getHeight();
    double imagePreferredSize = this.getConfiguration().getDouble("arrow.size") * size;
    double imageScaleFactor = (imageWidth > imageHeight) ? imagePreferredSize / imageWidth : imagePreferredSize / imageHeight;
       
    double rotationSin = Math.abs(Math.sin(direction));
    double rotationCos = Math.abs(Math.cos(direction));
    int imageNewWidth = (int)Math.floor(imageWidth * rotationCos + imageHeight * rotationSin);
    int imageNewHeight = (int)Math.floor(imageHeight * rotationCos + imageWidth * rotationSin);
    
    AffineTransform transform = new AffineTransform();
    transform.scale(imageScaleFactor, imageScaleFactor);
    transform.translate((imageNewWidth - imageWidth) / 2, (imageNewHeight - imageHeight) / 2);
    transform.rotate(direction, imageWidth / 2, imageHeight / 2);
    
    AffineTransformOp operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
    image = operation.filter(image, null);

    g2d.drawImage(image,
                 (int)((this.getWidth() - image.getWidth()) / 2),
                 (int)((this.getHeight() - image.getHeight()) / 2),
                 null);
}
 
Example 9
@Override
public Dimension render(Graphics2D graphics)
{
	if (consumers.isEmpty())
	{
		return null;
	}

	final MainBufferProvider bufferProvider = (MainBufferProvider) client.getBufferProvider();
	final int imageHeight = ((BufferedImage) bufferProvider.getImage()).getHeight();
	final int y = imageHeight - plugin.getReportButton().getHeight() - 1;

	graphics.drawImage(plugin.getReportButton(), REPORT_BUTTON_X_OFFSET, y, null);

	graphics.setFont(FontManager.getRunescapeSmallFont());
	FontMetrics fontMetrics = graphics.getFontMetrics();

	String date = DATE_FORMAT.format(new Date());
	final int dateWidth = fontMetrics.stringWidth(date);
	final int dateHeight = fontMetrics.getHeight();

	final int textX = REPORT_BUTTON_X_OFFSET + plugin.getReportButton().getWidth() / 2 - dateWidth / 2;
	final int textY = y + plugin.getReportButton().getHeight() / 2 + dateHeight / 2;

	graphics.setColor(Color.BLACK);
	graphics.drawString(date, textX + 1, textY + 1);

	graphics.setColor(Color.WHITE);
	graphics.drawString(date, textX, textY);

	// Request the queued screenshots to be taken,
	// now that the timestamp is visible.
	Consumer<Image> consumer;
	while ((consumer = consumers.poll()) != null)
	{
		drawManager.requestNextFrameListener(consumer);
	}

	return null;
}
 
Example 10
private void drawCardImage(Graphics2D g2d, BufferedImage image, Rectangle startRect, Rectangle endRect) {
    Rectangle drawRect = new Rectangle(
        startRect.x - (int) ((startRect.x - endRect.x) * timelinePulse),
        0,
        startRect.width + (int) ((endRect.width - startRect.width) * timelinePulse),
        startRect.height + (int) ((endRect.height - startRect.height) * timelinePulse)
    );
    g2d.drawImage(image, drawRect.x, drawRect.y, drawRect.width, drawRect.height, null);
}
 
Example 11
public static void main(String[] args) {

        /* Create an image to draw, filled in solid red. */
        BufferedImage srcImg =
             new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
        Graphics srcG = srcImg.createGraphics();
        srcG.setColor(Color.red);
        int w = srcImg.getWidth(null);
        int h = srcImg.getHeight(null);
        srcG.fillRect(0, 0, w, h);

        /* Create a destination image */
        BufferedImage dstImage =
           new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
        Graphics2D dstG = dstImage.createGraphics();
        /* draw image under a scaling transform that overflows int */
        AffineTransform tx = new AffineTransform(0.5, 0, 0, 0.5,
                                                  0, 5.8658460197478485E9);
        dstG.setTransform(tx);
        dstG.drawImage(srcImg, 0, 0, null );
        /* draw image under the same overflowing transform, cancelling
         * out the 0.5 scale on the graphics
         */
        dstG.drawImage(srcImg, 0, 0, 2*w, 2*h, null);
        if (Color.red.getRGB() == dstImage.getRGB(w/2, h/2)) {
             throw new RuntimeException("Unexpected color: clipping failed.");
        }
        System.out.println("Test Thread Completed");
    }
 
Example 12
Source Project: openAGV   File: LocationFigure.java    License: Apache License 2.0 5 votes vote down vote up
@Override  // AbstractAttributedFigure
protected void drawFill(Graphics2D g) {
  int dx;
  int dy;
  Rectangle r = displayBox();
  g.fillRect(r.x, r.y, r.width, r.height);

  if (fImage != null) {
    dx = (r.width - fImage.getWidth(this)) / 2;
    dy = (r.height - fImage.getHeight(this)) / 2;
    g.drawImage(fImage, r.x + dx, r.y + dy, this);
  }
}
 
Example 13
/**
 * Fonte: https://stackoverflow.com/questions/21382966/colorize-a-picture-in-java MODIFICADO
 *
 * @param image
 * @param color
 * @return
 */
public static BufferedImage dye(ImageIcon image, Color color) {
    int w = image.getIconWidth();
    int h = image.getIconHeight();
    BufferedImage dyed = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = dyed.createGraphics();
    g.drawImage(image.getImage(), 0, 0, null);
    g.setComposite(AlphaComposite.SrcAtop);
    g.setColor(color);
    g.fillRect(0, 0, w, h);
    g.dispose();
    return dyed;
}
 
Example 14
public static void main(String[] args) {

        /* Create an image to draw, filled in solid red. */
        BufferedImage srcImg =
             new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
        Graphics srcG = srcImg.createGraphics();
        srcG.setColor(Color.red);
        int w = srcImg.getWidth(null);
        int h = srcImg.getHeight(null);
        srcG.fillRect(0, 0, w, h);

        /* Create a destination image */
        BufferedImage dstImage =
           new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
        Graphics2D dstG = dstImage.createGraphics();
        /* draw image under a scaling transform that overflows int */
        AffineTransform tx = new AffineTransform(0.5, 0, 0, 0.5,
                                                  0, 5.8658460197478485E9);
        dstG.setTransform(tx);
        dstG.drawImage(srcImg, 0, 0, null );
        /* draw image under the same overflowing transform, cancelling
         * out the 0.5 scale on the graphics
         */
        dstG.drawImage(srcImg, 0, 0, 2*w, 2*h, null);
        if (Color.red.getRGB() == dstImage.getRGB(w/2, h/2)) {
             throw new RuntimeException("Unexpected color: clipping failed.");
        }
        System.out.println("Test Thread Completed");
    }
 
Example 15
@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 16
/**
 * ColorConverts the source BufferedImage.
 * If the destination image is null,
 * a BufferedImage will be created with an appropriate ColorModel.
 * @param src the source <code>BufferedImage</code> to be converted
 * @param dest the destination <code>BufferedImage</code>,
 *        or <code>null</code>
 * @return <code>dest</code> color converted from <code>src</code>
 *         or a new, converted <code>BufferedImage</code>
 *         if <code>dest</code> is <code>null</code>
 * @exception IllegalArgumentException if dest is null and this op was
 *             constructed using the constructor which takes only a
 *             RenderingHints argument, since the operation is ill defined.
 */
public final BufferedImage filter(BufferedImage src, BufferedImage dest) {
    ColorSpace srcColorSpace, destColorSpace;
    BufferedImage savdest = null;

    if (src.getColorModel() instanceof IndexColorModel) {
        IndexColorModel icm = (IndexColorModel) src.getColorModel();
        src = icm.convertToIntDiscrete(src.getRaster(), true);
    }
    srcColorSpace = src.getColorModel().getColorSpace();
    if (dest != null) {
        if (dest.getColorModel() instanceof IndexColorModel) {
            savdest = dest;
            dest = null;
            destColorSpace = null;
        } else {
            destColorSpace = dest.getColorModel().getColorSpace();
        }
    } else {
        destColorSpace = null;
    }

    if ((CSList != null) ||
        (!(srcColorSpace instanceof ICC_ColorSpace)) ||
        ((dest != null) &&
         (!(destColorSpace instanceof ICC_ColorSpace)))) {
        /* non-ICC case */
        dest = nonICCBIFilter(src, srcColorSpace, dest, destColorSpace);
    } else {
        dest = ICCBIFilter(src, srcColorSpace, dest, destColorSpace);
    }

    if (savdest != null) {
        Graphics2D big = savdest.createGraphics();
        try {
            big.drawImage(dest, 0, 0, null);
        } finally {
            big.dispose();
        }
        return savdest;
    } else {
        return dest;
    }
}
 
Example 17
@Override
public void draw(Graphics2D g2) {
	g2.drawImage(commons.colony().buildingInfoPanel, 0, 0, null);
	super.draw(g2);
}
 
Example 18
@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 19
Source Project: SVG-Android   File: AssetUtil.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Applies a {@link BufferedImageOp} on the given {@link BufferedImage}.
 *
 * @param source The source image.
 * @param op     The operation to perform.
 * @return A new image with the operation performed.
 */
public static BufferedImage operatedImage(BufferedImage source, BufferedImageOp op) {
    BufferedImage newImage = newArgbBufferedImage(source.getWidth(), source.getHeight());
    Graphics2D g = (Graphics2D) newImage.getGraphics();
    g.drawImage(source, op, 0, 0);
    return newImage;
}
 
Example 20
/**
 * Render the target image centered relative to the given rectangle.
 * @param g2 the graphics object
 * @param rect the target rectangle
 * @param image the image to render
 */
public static void drawCentered(Graphics2D g2, Rectangle rect, BufferedImage image) {
	int dw = (rect.width - image.getWidth()) / 2;
	int dh = (rect.height - image.getHeight()) / 2;
	g2.drawImage(image, rect.x + dw, rect.y + dh, null);
}