Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting transparent gif / png to jpeg using java
    text
    copied!<p>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:</p> <p><a href="http://img292.imageshack.us/img292/2103/indexedtestal7.gif">Input gif image http://img292.imageshack.us/img292/2103/indexedtestal7.gif</a></p> <p>[In case the image is missing: it's a blue circle with transparent pixels around it]</p> <p>When I convert this image using the following code:</p> <pre><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); </code></pre> <p>This code works without throwing an Exception, but results an invalid jpeg image:</p> <p><a href="http://img297.imageshack.us/img297/3493/indexedtest1qe5.jpg">Output jpeg image http://img297.imageshack.us/img297/3493/indexedtest1qe5.jpg</a></p> <p>[In case the image is missing: IE cannot show the jpeg, Firefox shows the image with invalid colors.]</p> <p>I'm using Java 1.5. </p> <p>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.</p> <p>Is it a bug in the JDK? How can I convert images correctly preferably without 3rd party libraries?</p> <p><strong>UPDATE:</strong></p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload