BufferedImage JPEG transparency using OpenJDK

Standard

When attempting to write a transparent JPEG to disk using OpenJDK 5,6,7 javax.imageio.IIOException error is thrown. This occurs because OpenJDK does not have a native JPEG encoder. There are two separate solutions.

Solution 1: Change the library

A alternative would be to switch from OpenJDK to Sun’s JDK which has a native JPEG encoder.

Solution 2: Buffered image write around

A programmatic way to solve the problem is to map or draw the existing BufferedImage onto a new BufferedImage with the type changed from TYPE_4BYTE_ABGR (default) to TYPE_3BYTE_BGR (new). The converted image will now be writable to disk.

// Read in the uploaded file
InputStream input = file.getInputstream();
BufferedImage originalImg = convertInputStreamToBufferedImage(input);

// Converts the buffered image to the required type then draws the original on top
BufferedImage convertedImg = new BufferedImage(originalImg.getWidth(), originalImg.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
convertedImg.getGraphics().drawImage(originalImg, 0, 0, null);
convertedImg.getGraphics().dispose();

// Write to disk
ImageIO.write(convertedImg, "jpeg", new File("/PATH/filename.jpg"));