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()
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.
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.
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.
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With