简体   繁体   中英

streaming a jpeg using com.sun.image.codec.jpeg.JPEGImageEncoder vs javax.imageio.ImageIO

I have a BufferedImage object of a jpeg which needs to be streamed as servlet response.

The existing code streams the jpeg using JPEGImageEncoder which looks like this :

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(resp.getOutputStream());
            resp.reset();
            resp.setContentType("image/jpg");
            resp.setHeader("Content-disposition", "inline;filename=xyz.jpg");
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
            param.setQuality(jpegQuality, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(image);

I have noticed that this is resulting in the file size of the streamed jpeg to be tripled , unable to figure why.So I have tried using ImageIO to stream the jpeg

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

This works just fine, I am unable to decide why my predecessor has gone with the choice of JPEGImageEncoder and was wondering what issues would arise if I change to using ImageIO, I have compared both jpegs and couldn't really spot differences. Any thoughts?

To be clear, you've already a concrete JPEG image somewhere on disk or in database and you just need to send it unmodified to the client? There's then indeed absolutely no reason to use JPEGImageEncoder (and ImageIO ).

Just stream it unmodified to the response body.

Eg

File file = new File("/path/to/image.jpg");
response.setContentType("image/jpeg");
response.setHeader("Content-Length", String.valueOf(file.length()));

InputStream input = new FileInputStream(file);
OutputStream output = response.getOutputStream();
byte[] buffer = new byte[8192];

try {
    for (int length = 0; (length = input.read(buffer)) > 0;) {
        output.write(buffer, 0, length);
    }
}
finally {
    try { input.close(); } catch (IOException ignore) {}
    try { output.close(); } catch (IOException ignore) {}
}

You see the mistake of unnecessarily using JPEGImageEncoder (and ImageIO ) to stream image files often back in code of starters who are ignorant about the nature of bits and bytes. Those tools are only useful if you want to convert between JPEG and a different image format, or want to manipulate (crop, skew, rotate, resize, etc) it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM