Question

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...!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top