我编写了一个类,它可以帮助我从一个大图中获取32x32图像。但我有一个问题。我的班级看起来像这样:
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];
}
}
如果我这样做,似乎ImageIO.read(new File(String file))
命令阻止使用那个我想绘制图像的Swing对象的paintComponent()
。我进行了一些实验,发现当你在getSubImage(int X, int Y)
方法中加载图像时,它运行正常。但我想,这不是最明智的想法,因为如果你调用这个方法,你总是会再次加载这个图像。我需要帮助,我如何只加载一次图像,并且Swing对象正确地绘制了它。
提前致谢。
答案 0 :(得分:0)
编写缩略图并将其加载回JLabel。
//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));