Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make jpeg lossless in java?

Is there someone that can tell me how to write 'jpeg' file using lossless compression in java?

I read the bytes using the code below to edit the bytes

WritableRaster raster = image.getRaster();
DataBufferByte buffer = (DataBufferByte) raster.getDataBuffer();

And I need to write again the bytes as 'jpeg' file without compressing in lossy.

like image 360
Ran Gualberto Avatar asked Oct 01 '11 07:10

Ran Gualberto


1 Answers

The JAI package offers the ability to save “lossless JPEG” formats. Set compresion type to JPEG-LS or JPEG-LOSSLESS depending on what variant you want.

I'm not sure you really want lossless-JPEG though. It's a separate format that's not really much to do with the normal JPEG format. It is not, in general, very well-supported; for lossless image storage you are typically better off with something like PNG.

If you need to do lossless image transcoding (ie the set of cropping and rotation operations you can do without disturbing the boundaries of the DCT matrices), you would generally do it with the jpegtran command, as there's not currently a Java binding to the IJG library as far as I know.

ETA:

do you know how to do it with JAI.

I've not tried it myself (code below is untested), but it should be a straightforward call to setCompressionType. (Of course ‘straightforward’ in Java still means negotiating a maze of twisty little objects to set what would be a simple switch anywhere else:)

ImageWriter writer= (ImageWriter) ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam param= writer.getDefaultWriteParam();
param.setCompressionMode(param.MODE_EXPLICIT);
param.setCompressionType("JPEG-LS");
writer.setOutput(ImageIO.createImageOutputStream(new File(path)));
writer.write(null, new IIOImage(image, null, null), param);

JPEG-LS is the newer lossless JPEG standard. It compresses more than the original JPEG-LOSSLESS standard but support is even worse. Most applications that support JPEG will not be able to do anything with these.

like image 95
bobince Avatar answered Oct 13 '22 18:10

bobince