Question

Is there a Java library that can read regions of very large image (e.g. JPEG) files (> 10,000 x 10,000 pixels) without keeping the whole image in memory.

Or alternatively, which Java library is capable of handling very large image files with a minimum of overhead.

Was it helpful?

Solution

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
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top