How to make jpeg lossless in java?

2019-06-20 05:03发布

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.

1条回答
不美不萌又怎样
2楼-- · 2019-06-20 05:29

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.

查看更多
登录 后发表回答