javax.imageio.ImageReader loading the same image over and overagain Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of javax.imageio.ImageReader loading the same image over and overagain without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have some code which uses the ImageReader class to read in a large number of TIF images. The imageReader object is final and created in the constructor.

synchronized(imageReader) {
    FileInputStream fin = new FileInputStream(file);
    ImageInputStream iis = ImageIO.createImageInputStream(fin);
    imageReader.setInput(iis, false);
    int sourceXSubSampling = targetSize == null ?
            1 : Math.max(1, imageReader.getWidth(0) / targetSize.width);
    int sourceYSubSampling = targetSize == null ?
            1 : Math.max(1, imageReader.getHeight(0) / targetSize.height);
    ImageReadParam subSamplingParam = new ImageReadParam();
    subSamplingParam.setSourceSubsampling(sourceXSubSampling, sourceYSubSampling, 0, 0);
    return, subSamplingParam);

About one instance in four the ImageReader get “stuck” on the first image it loaded and keeps loading that same image over and over again even though it is provided with different ImageInputStreams. This is evidenced by the output to the logger.

How do I solve this. I was thinking about taking a “fingerprint” of the image and getting a different ImageReader from the iterator if this occurs but that seems like overkill. Does anyone know how to solve this problem?


As @MadProgrammer says in the comment section, the typical pattern for reading multiple images is to obtain a new ImageReader for each image, and afterwards dispose() it. The time/memory spent on creating a reader instance is very small, compared to actually reading an image. So any performance penalty should be negligible.

In theory it should, however, be sufficient to invoke reset() on the ImageReader before/after each read.

We are here to answer your question about javax.imageio.ImageReader loading the same image over and overagain - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji