Question

I'm thinking about the best way to do two things in Java:

  1. merge two images, the background one in .PNG and the other in .GIF or .PNG (has transparency and is to overlap the first one);
  2. convert the merged image to .GIF (with transparency).

I don't want to render them, just to handle the images in the java class and write the resultant image to a file.

Can anyone help me? What's the best way to do this? Thank you!

EDIT: Thank you all for the suggestions! This was what I ended up using! Pretty simple!

BufferedImage background = ImageIO.read(new File("image.jpg"));
WritableRaster raster = background.getRaster();
BufferedImage layer = ImageIO.read(new File("overlay.png"));
Graphics2D g2d = (Graphics2D)background.getGraphics();
g2d.drawImage(layer,72,80,null);

About the second problem, I still can't save this with .gif extension with transparency. This

ImageIO.write(bufferedImage,"gif",file);

creates the .gif image file but it loses the transparency! Does anyone know how can I do this? JAI also doesn't have the gif encoder. Thank you.

Was it helpful?

Solution

Not sure of your application, but if this is server-based high performance stuff, I've had much better results shelling out to ImageMagick than using Java's image libraries.

OTHER TIPS

Maybe this link could help ?

It is the same to render an image on a component and to paint an image.

Instead of painting in the paint method, you'll have to create a method createImage(). The sample provided in the link could be adapted like this: (in java, painting on a component, on an image, on printer output... is everywhere the same. You get a graphics, you paint).

public BufferedImage createImage(Graphics g) {
    BufferedImage image - new BufferedImage(...);



    Graphics2D g2 = image.getGraphics();

    Point2D center =  new Point2D.Float(image.getHeight( ) / 2, image.getWidth( ) / 2);
    AffineTransform at = AffineTransform.getTranslateInstance(center.getX( ) - (bi2.getWidth( ) / 2), center.getY( ) - (bi2.getHeight( ) / 2));

    g2.transform(at);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.drawImage(bi2, 0, 0, null);

    Composite c = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .35f);
    g2.setComposite(c);

    at = AffineTransform.getTranslateInstance(center.getX( ) - (bi1.getWidth( ) / 2), center.getY( ) - (bi1.getHeight( ) / 2));
    g2.setTransform(at);
    g2.drawImage(bi1, 0, 0, null);

    return image;
}

If you don't mind adding an external dependency, you can use the JMagick bindings to ImageMagick.

Definintely check out JAI (api).

It will allow you to load and store images that were encoded in basically any known format (png and gif included) and allow you to efficiently operate on the images once they've been loaded.

In particular you're probably looking for something like the CompositeDescriptor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top