Memory leak in java ImageIO.read()

前端 未结 1 1985
面向向阳花
面向向阳花 2021-01-18 15:54

I am utilizing ImageIO.read(). The class which is called by the main method of the original App is this:

import java.awt.*;
import javax.swing.*;
import java         


        
相关标签:
1条回答
  • 2021-01-18 16:17

    I have got the same memory issue with this code (JPEGReader). After a few trials, I found that calling reader.dispose() can solve this issue.

    I give the method that I have modified. Hope it is helpful to you.

    public BufferedImage readImage(File file) throws IOException, ImageReadException {
        colorType = COLOR_TYPE_RGB;
        hasAdobeMarker = false;
    
        ImageInputStream stream = ImageIO.createImageInputStream(file);
        try{
            Iterator<ImageReader> iter = ImageIO.getImageReaders(stream);
            while (iter.hasNext()) {
                ImageReader reader = iter.next();
                reader.setInput(stream);
    
                BufferedImage image;
                ICC_Profile profile = null;
                try {
                    image = reader.read(0);
                } catch (IIOException e) {
                    colorType = COLOR_TYPE_CMYK;
                    checkAdobeMarker(file);
                    profile = Sanselan.getICCProfile(file);
                    WritableRaster raster = (WritableRaster) reader.readRaster(0, null);
                    if (colorType == COLOR_TYPE_YCCK)
                        convertYcckToCmyk(raster);
                    if (hasAdobeMarker)
                        convertInvertedColors(raster);
                    image = convertCmykToRgb(raster, profile);
                    return image;
                }
                finally {
                    reader.dispose();
                }
            }
            return null;
        }
        finally {
            if (stream != null){
                stream.close();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题