-1

I programmed a class, which helps me to get 32x32 images from a large one. But I have a problem. My class looks like this:

package tool;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageLoader {

    private String file;
    private BufferedImage image;
    private BufferedImage[][] subImage;

    public ImageLoader(String FILE) {
        file = FILE;
        try {
            image = ImageIO.read(new File(file));
        } catch (IOException e) {
        }

        subImage = new BufferedImage[image.getWidth() / 32][image.getHeight() / 32];
        for (int i = 0; i < image.getWidth() / 32; i++) {
            for (int j = 0; j < image.getHeight() / 32; j++) {
                subImage[i][j] = image.getSubimage(i * 32, j * 32, (1 + i) * 32, (1 + j) * 32);
            }
        }
    }

    public BufferedImage getSubImage(int X, int Y) {
        return subImage[X][Y];
    }
}

If I do it that way, it seems the ImageIO.read(new File(String file)) command prevents the use of paintComponent() of that Swing object, where I want to draw the image. I experimented a little bit and found out, that when you load the image in the getSubImage(int X, int Y) method, it works fine. But I think, it's not the smartest idea, because then you always load this image again, if you call the method. I need help, how I can load that image just one time and that the Swing object draw everthing correctly.

Thanks in advance.

Harald K
  • 26,314
  • 7
  • 65
  • 111
  • How does `ImageIO.read(file)` prevent the use of `paintComponent()`? There's no Swing components in your code...? – Harald K Jan 28 '14 at 18:32

1 Answers1

0

Write the thumbnail and load it back in a JLabel instead.

//get the large file and create a new 32x32 thumbnail 
BufferedImage sourceImage = ImageIO.read(new FileInputStream("c://filename"));
Image thumbnail = sourceImage.getScaledInstance(32, 32, Image.SCALE_SMOOTH);
BufferedImage bufferedThumbnail = new BufferedImage(thumbnail.getWidth(null),
                                                thumbnail.getHeight(null),
                                                BufferedImage.TYPE_INT_RGB); 
bufferedThumbnail.getGraphics().drawImage(thumbnail, 0, 0, null);
//read the file back
ImageIO.write(bufferedThumbnail, "jpeg", outputStream);


//read the file back  
image = ImageIO.read(new File(path));
JLabel picLabel = new JLabel(new ImageIcon(image));
Sorter
  • 9,704
  • 6
  • 64
  • 74