I'm having trouble converting PNG from Alpha to JPEG from the Wiki.
This image is: http://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/Radio_SRF_3.svg/500px-Radio_SRF_3.svg.png
Original: 
The converted JPEG file has the wrong color. Now it is more gray than darker. 
This is how I do the conversion:
Delete alpha:
public static BufferedImage imageFillAlphaWithColor(BufferedImage image, Color fillColor) { if (image.getColorModel().getTransparency() == Transparency.OPAQUE) return image; int w = image.getWidth(); int h = image.getHeight(); BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = newImage.createGraphics(); g.drawImage(image, 0, 0, fillColor, null); g.dispose(); return newImage; }
Jpeg compression:
public static byte[] compressedJpegImage(BufferedImage image, float quality) { byte jpegImage[] = null; try { // Find a jpeg writer ImageWriter writer = null; Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg"); if (iter.hasNext()) { writer = (ImageWriter) iter.next(); } // Prepare output ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(os); writer.setOutput(ios); // Set the compression quality ImageWriteParam iwparam = writer.getDefaultWriteParam(); iwparam.setProgressiveMode(ImageWriteParam.MODE_DEFAULT); iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwparam.setCompressionQuality(quality); // Write the image writer.write(null, new IIOImage(image, null, null), iwparam); // Cleanup ios.flush(); writer.dispose(); ios.close(); jpegImage = os.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return jpegImage; }
And save it as JPEG using ImageIO.
Any idea how to preserve the color space in order to preserve the colors as they are in the original?
UPDATE
The problem was caused by ImageMagick when resizing. ImageMagick seems to have changed the color space to TYPE_CUSTOM, and Java can't handle it.
Current solution:
Remove alpha before I start resizing the image using ImageMagick.
No solution has yet been found to convert the color space from "CUSTOM" back to "ARGB". So this is just a "workaround" for this problem.
java colors png alpha jpeg
Arny
source share