Java image scaling without loading the whole image into memory

女生的网名这么多〃 提交于 2021-02-07 20:54:59

问题


We have some very large jpgs which are used when print on A0 printers.

The problem is that we need to convert this large image down to a thumbnail for use in a few java UIs.

Is there any way to convert the image (with Java) without loading the whole image into memory? Currently we get out of memory exceptions when we try to load the images.

Is there anything in the standard code or is my best bet to use jmagick? A pure java implementation would be best for our deployment.

Thanks


回答1:


I managed to get it working and the full code is as follows.

The call to reader.setInput(iis, true, true); is the magic which I was missing from the previous post.

FileInputStream fin = new FileInputStream(source);

ImageInputStream iis = ImageIO.createImageInputStream(fin);

Iterator iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
    return;
}

ImageReader reader = (ImageReader) iter.next();

ImageReadParam params = reader.getDefaultReadParam();

reader.setInput(iis, true, true);

params.setSourceSubsampling(width, height, 0, 0);

BufferedImage img = reader.read(0, params);

ImageIO.write(img, "JPG", destination);


来源:https://stackoverflow.com/questions/10817597/java-image-scaling-without-loading-the-whole-image-into-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!