How to prevent loss of image quality while using ImageIO.write() method?

寵の児 提交于 2019-12-24 04:31:47

问题


I am dealing with Images in java where I do read and write Images in my local disk. My Problem is while writing Images I am losing the quality of the actual Image I read. It reduces the quality by image file size from 6.19MB(actual image size) file to 1.22MB(written using ImageIO.write() which is drastic loss. How can I prevent this loss when i do use

 ImageIO.write(image, "jpg", os);

for writing Image. Remember, I dont need any compression over here. Just I want to read the Image and write the same image with same quality and same file Size. I also tried,

writer.write(null, new IIOImage(image, null, null), param);

but it takes my execution time more and does a compression process.

Please help me out in this. Is there any chance to write lossless image quality using

 ImageIO.write(image, "jpg", os);

or any other way?

Thanks in advance...!


回答1:


You seem to be a little confused about JPEG "compression" and "quality" (and I partly blame the ImageIO API for that, as they named the setting "compressionQuality").

JPEG is always going to compress. That's the point of the format. If you don't want compression, JPEG is not the format you want to use. Try uncompressed TIFF or BMP. As the commenters have already said, normal JPEG is always going to be lossy (JPEG-LS and JPEG Lossless are really different algorithms btw).

If you still want to go with JPEG, here's some help. Unfortunately, there's no way to control the "compressionQuality" setting using:

ImageIO.write(image, "jpg", os);

You need to use the more verbose form:

ImageReader reader = ...;
reader.setInput(...);
IIOImage image = reader.readAll(0, null); // Important, also read metadata

RenderedImage renderedImage = image.getRenderedImage();

// Modify renderedImage as you like

ImageWriter writer = ImageIO.getImageWriter(reader);
ImageWriteParam param = writer.getDefaultWriteParam();
paran.setCompressionMode(MODE_COPY_FROM_METADATA); // This modes ensures closest to original compression

writer.setOutput(...);
writer.write(null, image, param); // Write image along with original meta data

Note: try/finally blocks and stream close()and reader/writer dispose() omitted for clarity. You'll want them in real code. :-)

And this shouldn't really make your execution time noticeably longer, as ImageIO.write(...) uses similar code internally.



来源:https://stackoverflow.com/questions/21204627/how-to-prevent-loss-of-image-quality-while-using-imageio-write-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!