package bugs.jpeg; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * This test program demonstrates a critical bug in the * JPEG writer of ImageIO. When a BufferedImage is written * to a JPEG file all colors are garbled if the BufferdImage * contains an alpha channel. As JPEG does not support * an alpha channel the writer should just ignore it * but otherwise leave the colors intact. * * This bug is especially critical for JavaFX users because * all JavaFX images converted to BufferedImages do contain * an alpha channel and converting to a BufferdImage and writing * in out via ImageIO is the only way to write an image in JavaFX. * * This was also reported as: * http://javafx-jira.kenai.com/browse/RT-23502 * * @author M. Paus */ public class ImageIOJpegBug { static final String IMG_FORMAT = "jpeg"; static final int[] IMG_TYPES = new int[]{ BufferedImage.TYPE_INT_RGB, // 1 - ok BufferedImage.TYPE_INT_ARGB, // 2 - wrong BufferedImage.TYPE_INT_ARGB_PRE, // 3 - wrong BufferedImage.TYPE_INT_BGR, // 4 - ok BufferedImage.TYPE_3BYTE_BGR, // 5 - ok BufferedImage.TYPE_4BYTE_ABGR, // 6 - wrong BufferedImage.TYPE_4BYTE_ABGR_PRE, // 7 - wrong BufferedImage.TYPE_USHORT_565_RGB, // 8 - ok BufferedImage.TYPE_USHORT_555_RGB, // 9 - ok }; public static void main(String[] args) { for (int imgType : IMG_TYPES) { BufferedImage bi = new BufferedImage(600, 400, imgType); Graphics2D g2 = (Graphics2D)bi.getGraphics(); g2.setColor(Color.WHITE); g2.fillRect(0, 0, bi.getWidth(), bi.getHeight()); g2.setColor(Color.RED); g2.drawString("RED", 100, 100); g2.setColor(Color.GREEN); g2.drawString("GREEN", 200, 200); g2.setColor(Color.BLUE); g2.drawString("BLUE", 300, 300); try { String filename = "image_type" + imgType + "." + IMG_FORMAT; ImageIO.write(bi, IMG_FORMAT, new File(filename)); System.out.println(filename + " written."); } catch (IOException e) { e.printStackTrace(); } } } }