Converting transparent gif / png to jpeg using java

asalamon74 picture asalamon74 · Jan 21, 2009 · Viewed 27.5k times · Source

I'd like to convert gif images to jpeg using Java. It works great for most images, but I have a simple transparent gif image:

Input gif image http://img292.imageshack.us/img292/2103/indexedtestal7.gif

[In case the image is missing: it's a blue circle with transparent pixels around it]

When I convert this image using the following code:

File file = new File("indexed_test.gif");
BufferedImage image = ImageIO.read(file);
File f = new File("indexed_test.jpg");
ImageIO.write(image, "jpg", f);

This code works without throwing an Exception, but results an invalid jpeg image:

Output jpeg image

[In case the image is missing: IE cannot show the jpeg, Firefox shows the image with invalid colors.]

I'm using Java 1.5.

I also tried converting the sample gif to png with gimp and using the png as an input for the Java code. The result is the same.

Is it a bug in the JDK? How can I convert images correctly preferably without 3rd party libraries?

UPDATE:

Answers indicate that jpeg conversion cannot handle transparency correctly (I still think that this is a bug) and suggest a workaround for replacing transparent pixels with predefined color. Both of the suggested methods are quite complex, so I've implemented a simpler one (will post as an answer). I accept the first published answer with this workaround (by Markus). I don't know which implementation is the better. I go for the simplest one still I found a gif where it's not working.

Answer

Lana picture Lana · Oct 9, 2009

For Java 6 (and 5 too, I think):

BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
g = bufferedImage.createGraphics();
//Color.WHITE estes the background to white. You can use any other color
g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, null);