gpt4 book ai didi

java - 从 byte[] 类型的像素构建按比例缩小的 ImageIcon 的最有效方法是什么?

转载 作者:行者123 更新时间:2023-11-30 09:39:49 24 4
gpt4 key购买 nike

我使用以下语句将图像像素保存在字节数组中:

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。缓冲图像,每像素 4 个字节 100 MB 将是:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com