问题描述
我想在我的应用程序中加载大图像(18000 x 18000)。如果我使用类型 int_rgb
的 BufferedImage
,我需要加载大约1235mb的堆内存。这是一个非常大的内存量,最终用户可能会有更少的内存(1GB或更少)。
I want to load large images (18000 x 18000) to my application. If i use BufferedImage
with type int_rgb
, I need around 1235mb of heap memory to load. This is a very high amount of memory, and end users will likely have less ram (1GB or less).
在我的开发PC上,当我从MyEclipse加载图像时IDE,它会抛出内存不足异常
。当我将我的代码打包到一个可执行jar并在Eclipse外部的PC上运行时,它仍然会抛出异常。
On my development PC, when I load the image from MyEclipse IDE, it throws an out of memory Exception
. When i pack my code to an executable jar and run it on my PC external of Eclipse, it still throws an exception.
如何在不使用1235mb内存的情况下使用缓冲图像将如此大的图像加载到我的应用程序中?有没有一个技巧,比如将图像分成像图像分割这样的较小部分?
How do I load such a large image into my application using buffered image without using 1235mb of memory? Is there a trick, like splitting the image into smaller portions like image segmentation?
我发现,但它对我没用;我想将图像加载到 BufferedImage
中,然后使用 Graphics在
class。 Panel
上绘制它
I found this thread on SO, but it not useful for me; I want to load the image into BufferedImage
and then draw it on a Panel
using the Graphics
class.
推荐答案
您可以使用来自 ImageIO
包裹。这是一个基本示例,说明如何使用 ImageReadParam
读取单个片段而不读取整个图像:
You can read and display fragments of the image using ImageReadParam from ImageIO
package. Here is a basic example that illustrates how to read a single fragment using ImageReadParam
without reading the whole image:
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
public class TestImageChunks {
private static void createAndShowUI() {
try {
URL url = new URL(
"http://duke.kenai.com/wave/.Midsize/Wave.png.png");
Image chunk = readFragment(url.openStream(), new Rectangle(150,
150, 300, 250));
JOptionPane.showMessageDialog(null, new ImageIcon(chunk), "Duke",
JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
public static BufferedImage readFragment(InputStream stream, Rectangle rect)
throws IOException {
ImageInputStream imageStream = ImageIO.createImageInputStream(stream);
ImageReader reader = ImageIO.getImageReaders(imageStream).next();
ImageReadParam param = reader.getDefaultReadParam();
param.setSourceRegion(rect);
reader.setInput(imageStream, true, true);
BufferedImage image = reader.read(0, param);
reader.dispose();
imageStream.close();
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
结果如下:
这篇关于如何通过BufferedImage将巨大的图像加载到Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!