Read region from very large image file in Java

[亡魂溺海] 提交于 2019-11-27 22:30:45

Standard ImageIO allows you to read regions of (large) images without reading the entire image into memory first.

Rectangle sourceRegion = new Rectangle(x, y, w, h); // The region you want to extract

ImageInputStream stream = ImageIO.createImageInputStream(input); // File or input stream
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);

if (readers.hasNext()) {
    ImageReader reader = readers.next();
    reader.setInput(stream);

    ImageReadParam param = reader.getDefaultReadParam();
    param.setSourceRegion(sourceRegion); // Set region

    BufferedImage image = reader.read(0, param); // Will read only the region specified
}

You can use, for example, RandomAccessFile to read from the middle of the file: but the issue is that whole jpeg image is compressed after DCT quantization (http://www.fileformat.info/mirror/egff/ch09_06.htm), so I don't think that it is possible to read a fragment without reading whole file to memory.

You can use a BufferedImage to do what you need.

// Set these variables according to your requirements
int regionX, regionY, regionWidth, regionHeight;    

BufferedImage image = ImageIO.read(new File("/path/to/image.jpg"));
BufferedImage region = image.getSubimage(regionX, regionY, regionWidth, regionHeight);

And then you can process the region subimage however you want.

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