3

I have low information about the image files.

To be able to convert PNG to JPEG in Java, at first I have used below code part to convert PNG to JPEG: inverted

Code Part 1)

BufferedImage newBufferedImage = new BufferedImage(bufferedImageFile.getWidth(), bufferedImageFile.getHeight(),
        BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bufferedImageFile, 0, 0, Color.WHITE, null);
File retTempFile = MakeupFileUtil.createTempFile(fileName);
ImageIO.write(newBufferedImage, "jpg", retTempFile);
return retTempFile;

This accomplishes the task very well but the output quality is lower than the original PNG image quality(let's say PNG quality is 100 but JPEG quality is 75)

Then, from this answer, I tried below code part which uses "Compression Quality":

Code Part 2)

JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(1f);
final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(new FileImageOutputStream(jpegFile));
writer.write(null, new IIOImage(bufferedImageFile, null, null), jpegParams);

But this time, converted JPEG file got inverted colors.

Source Image (PNG): source png image

Image After Code Part 2 (JPEG): part 2 code result jpeg

Why is this happening?

Community
  • 1
  • 1
Bahadir Tasdemir
  • 10,325
  • 4
  • 49
  • 61

1 Answers1

2

Try and write newBufferedImage and not bufferedImageFile on "Code part 2".

So change this line to be:

writer.write(null, new IIOImage(newBufferedImage, null, null), jpegParams);

If you try and write a PNG image in JPEG format your going to end up with weird results.

ug_
  • 11,267
  • 2
  • 35
  • 52