Loading large images as thumbnails without memory issues in Java?

后端 未结 2 1282
挽巷
挽巷 2020-12-09 11:49

I\'m trying to let the user load images from their harddrive, and present these visually in the GUI as a list of thumbnails (JPanels with icons added to a JList). I\'m curre

2条回答
  •  余生分开走
    2020-12-09 12:38

    The problem is in the use of BufferedImage itself. By the time the file is read into memory you'll be out of heap space. Depending on what this is for you can either use an image reader or you can increase the size of the heap.

    I'd recommend that you use an image reader. For example to get an image reader you code would be something like this:

      // Create an image input stream on the image
        ImageInputStream iis = ImageIO.createImageInputStream(o);
    
        // Find all image readers that recognize the image format
        Iterator iter = ImageIO.getImageReaders(iis);
        if (!iter.hasNext()) {
            // No readers found
            return null;
        }
    
        // Use the first reader
        ImageReader reader = (ImageReader)iter.next();
    

    From : http://www.exampledepot.com/egs/javax.imageio/DiscType.html

    One you have the ImageReader you can get the aspect ration by calling reader.getAspectRatio()

    I'm not sure how you'd go from an ImageReader to a thumbnail though.

提交回复
热议问题