2015-01-27 116 views
0

我有一个要求使用读取一些专有图像文件格式(有关不重新发明我们自己的车轮)的本机库。图书馆工作正常,只是有时图像可以变得非常大(我见过的记录是13k x 15k像素)。问题是我可怜的JVM一直在痛苦的死亡和/或抛出OutOfMemoryError的任何时候图像开始变得巨大。将原始像素数据(作为字节数组)转换为BufferedImage

这里是我已经运行

//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; 
} 

这段代码的伟大工程,对于大多数图像,只要他们不是肮脏的大。它的速度也很好。问题在于,Image画到BufferedImage的步骤吞下太多内存。

有没有一种方法可以跳过这一步,直接从原始字节到缓冲图像?

回答

2

使用jai的RawImageInputStream。这确实需要了解有关SampleModel的信息,这些信息似乎来自本机代码。

另一种选择是将您的rawBytes放入DataBuffer,然后create a WritableRaster,最后创建一个BufferedImage。 这实质上就是RawImageInputStream的功能。

+0

由于内存使用似乎是这里的问题,后面的选项可能是最好的,因为你可以直接从原始字节数组(即'new DataBufferByte(rawBytes,rawBytes.length)'')创建'DataBuffer') 。 – haraldK 2015-01-27 08:53:29

+0

美丽的事情,男性。精彩的工作。 – captainroxors 2015-01-27 17:48:25