Question

I am working on an application which takes images in a folder and shows them as thumbnails for further selection and operation individually. below is the code that adds them to Jtogglebuttons.

toglBtn=new JToggleButton(""+i,new ImageIcon(ImageIO.read(new File(listOfFiles[i].getAbsolutePath())).getScaledInstance(139, 163, BufferedImage.SCALE_SMOOTH)));

My original images in the folder are <100kb but the Jtogglebutton size is 6mb. Is there any way to reduce the size of these? currently its taking up all my heap space and giving me an out of memory error when ever there are more than 40 files. I already increased the heap size to 512MB but after analyzing heap dumps with MAT, i figured i need to reduce the thumbnailsizes to solve this error.

Is there any way i can force the thumbnail to be a jpeg? or any other way of adding thumbnails to jtogglebuttons?

Final Update: I used thumbnailator to get the size of the button down to a few kb

try{
                            BufferedImage originalImage = ImageIO.read(new File(listOfFiles[i].getAbsolutePath()));                             
                            Image image =Thumbnails.of(originalImage).size(138, 163).asBufferedImage();
                            toglBtn=new JToggleButton(""+i,new ImageIcon(image));
                            }
Was it helpful?

Solution

Perhaps your one Java line is keeping the original image, the scaled image, and the image icon in memory.

Breaking up the code by doing it this way ensures that the original image and scaled image are dropped for garbage collection.

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JToggleButton;

    String text = "" + i;
    File imageFile = new File(listOfFiles[i].getAbsolutePath());
    BufferedImage image = ImageIO.read(imageFile);
    Image scaledImage = image.getScaledInstance(139, 163, 
            BufferedImage.SCALE_SMOOTH);
    ImageIcon imageIcon = new ImageIcon(scaledImage);
    toglBtn = new JToggleButton(text, imageIcon);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top