我使用以下语句将图像像素保存在字节数组中:
bytePixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
现在我需要构建图像的缩小版本,并使用此字节数组将其放入 ImageIcon 中。请注意,原始图像可能很大,因此构建一个新的 BufferedImage 如下:
public Icon getImageIcon(int newWidth, int newHeight) throws IOException {
BufferedImage image = ImageIO.read(originalImageFile);
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, this.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
g.dispose();
return new ImageIcon(resizedImage);
}
不是一个选项,因为如果原始图像很大,它很可能会导致 OutOfMemoryError。
所以我的问题是:使用字节数组中的原始像素,获得较小尺寸的 ImageIcon 的最有效方法(内存方面)是什么?
最佳答案
OutOfMemory 错误,这很奇怪。默认的 JVM 堆大小相当大。最有可能的是,它超过 100 MB。缓冲图像,100 MB 每像素 4 字节将是:
100 000 000 = x * 4 bytes
x = 25 000 000 pixels
这意味着您正在使用近 5000 * 5000 像素的图像。尝试使用以下命令行参数扩大最大堆大小:
java -XmX400M YourClass
此外,我不会使用字节数组存储像素。但只是作为 BufferedImage,这样您就可以确保图像数据不会在内存中出现两次。
关于java - 从 byte[] 类型的像素构建缩小的 ImageIcon 最有效的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9688312/