开发者

Creating JPEGs: converting access restricted code (JPEGImageEncoder) to "safe" code

开发者 https://www.devze.com 2023-01-30 07:20 出处:网络
I was given the following code, and Eclipse marked it (at the JPEGImageEncoder line) as an error (Access restriction). I changed Eclipse options to make that code compile, but I read that the error me

I was given the following code, and Eclipse marked it (at the JPEGImageEncoder line) as an error (Access restriction). I changed Eclipse options to make that code compile, but I read that the error means that that class (JPEGImageEncoder) may not be implemented by some JRE implementation (not a Sun/Oracle one).

So, what should be the code that wouldn't have access restrictions, i.e. completely safe code to do the same thing (create a 开发者_运维问答JPG image)?

BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(buffImage);
param.setQuality(0.8f, false);
encoder.encode(buffImage, param);


Maybe I've misunderstood, but if all you're looking to do is save a BufferedImage object as a jpeg, you can do this (from Java 1.4 onwards):

ImageIO.write(bufferedImage,"jpg",file);

Here's a link with more information: http://download.oracle.com/javase/tutorial/2d/images/saveimage.html

As you can see, it says that JPEG, PNG, GIF, BMP and WBMP will always be supported.

If you want to set the compression/quality, it's a little more work but not too much. Assuming you have a bufferedImage and an outFile:

IIOImage outputImage = new IIOImage(bufferedImage, null, null);

ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();        
writer.setOutput(new FileImageOutputStream(outFile));
ImageWriteParam writeParam = writer.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(.75f); // float between 0 and 1, 1 for max quality.
writer.write( null, outputImage, writeParam);

(fixed from previous answer)

0

精彩评论

暂无评论...
验证码 换一张
取 消