Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quality loss using ImageIO.write

I have noticied significant quality loss using ImageIO.write, how I can disable automatic compression ?

val baos: ByteArrayOutputStream = new ByteArrayOutputStream
val newBi = new BufferedImage(img.getWidth, img.getHeight, BufferedImage.TYPE_INT_RGB)
val gr = newBi.createGraphics()
gr.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), Color.WHITE, null)
ImageIO.write(newBi, "jpeg", baos)
val b = baos.toByteArray
baos.close()
like image 481
Roch Avatar asked Jun 09 '13 23:06

Roch


People also ask

What does ImageIO. write do?

The ImageIO. write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats. But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

What is ImageIO in Java?

ImageIO. A class containing static convenience methods for locating ImageReader s and ImageWriter s, and performing simple encoding and decoding. ImageReader. An abstract superclass for parsing and decoding of images.

How do you save BufferedImage?

You can save a BufferedImage as a GIF by specifying "GIF" as the format name to ImageIO. write(). Note that this will create a 256-colour indexed image.


2 Answers

Use ImageWriter.

ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // Needed see javadoc
param.setCompressionQuality(1.0F); // Highest quality
writer.write(image);

For non-photo images use .png.


As @PiotrekDe commented, the following seems more logical.

writer.write(null, new IIOImage(image, null, null), param)
like image 176
Joop Eggen Avatar answered Oct 21 '22 21:10

Joop Eggen


JPEG Cmpression is lossy. But PNG compression is lossless. So, i suggest to write in png format. That means you won't loss quality even if you compress in PNG format. Simple lines:

ImageIO.write(newBI,"png",someOutputStream);

But, if you want it in jpg format with quality, set Quality to 100%. The following code may help you.

    ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
    ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam();
    jpgWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    jpgWriteParam.setCompressionQuality(1f);
    jpgWriter.setOutput(someOutputStream);
     //better to use ImageOutputStream
    jpgWriter.write(null,new IIOImage(yourImage, null, null), jpgWriteParam);
like image 2
Mohammed Shareef C Avatar answered Oct 21 '22 20:10

Mohammed Shareef C