【发布时间】:2015-01-27 01:37:23
【问题描述】:
我需要使用读取一些专有图像文件格式的本机库(关于不重新发明我们自己的轮子)。该库工作正常,只是有时图像会变得很大(我看到的记录是 13k x 15k 像素)。问题是我可怜的 JVM 一直在痛苦地死去和/或在图像开始变大时抛出 OutOfMemoryError。
这是我正在运行的内容
//the bands, width, and height fields are set in the native code
//And the rawBytes array is also populated in the native code.
public BufferedImage getImage(){
int type = bands == 1 ? BufferedImage.TYPE_BYTE_GRAY : BufferedImage.TYPE_INT_BRG;
BufferedImage bi = new BufferedImage(width, height, type);
ImageFilter filter = new RGBImageFilter(){
@Override
public int filterRGB(int x, int y, int rgb){
int r, g, b;
if (bands == 3) {
r = (((int) rawBytes[y * (width / bands) * 3 + x * 3 + 2]) & 0xFF) << 16;
g = (((int) rawBytes[y * (width / bands) * 3 + x * 3 + 1]) & 0xFF) << 8;
b = (((int) rawBytes[y * (width / bands) * 3 + x * 3 + 0]) & 0xFF);
} else {
b = (((int) rawBytes[y * width + x]) & 0xFF);
g = b << 8;
r = b << 16;
}
return 0xFF000000 | r | g | b;
}
};
//this is the problematic block
ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
Image i = Toolkit.getDefaultToolkit().createImage(ip);
Graphics g = bi.createGraphics();
//with this next line being where the error tends to occur.
g.drawImage(i, 0, 0, null);
return bi;
}
这个 sn-p 适用于大多数图像,只要它们不是太大。它的速度也刚刚好。问题是Image 绘制到BufferedImage 步骤会占用太多内存。
有没有办法可以跳过这一步,直接从原始字节转到缓冲图像?
【问题讨论】:
标签: java bytearray bufferedimage imagefilter