2017-05-28 55 views
0

我有原始灰度图像像素由short[]表示。我想创建BufferedImage并将其保存为PNG。 由于没有TYPE_SHORT_GRAY定义BufferedImage我创建一个自己这样说:保存自定义BufferedImage

short[] myRawImageData; 

// Create signed 16 bit data buffer, and compatible sample model 
DataBuffer dataBuffer = new DataBufferShort(myRawImageData, w * h); 
SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_SHORT, w, h, 1, w, new int[] {0}); 

// Create a raster from sample model and data buffer 
WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, null); 

// Create a 16 bit signed gray color model 
ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY); 
ColorModel colorModel = new ComponentColorModel(colorSpace, false, false, Transparency.OPAQUE, DataBuffer.TYPE_SHORT); 

// Finally create the signed 16 bit image 
BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null); 

try (FileOutputStream fos = new FileOutputStream("/tmp/tst.png")) { 
    ImageIO.write(image, "png", fos);// <--- Here goes the exception 
} catch (Exception ex) { 
    ex.printStackTrace(); 
} 

到目前为止好,但是当我试图用ImageIO.write将它保存为PNG我越来越ArrayIndexOutOfBoundsException

+0

您应该a)将演示您的问题的代码发布为[MCVE],并且b)描述发生的事情,您希望发生的事情,它们之间的差异以及遇到的具体错误。 – pvg

回答

0

您的代码对我来说工作正常,我得到您的错误的唯一方法是当我更改bandOffset。你能给我们更多你的代码吗?

编辑 如果您的数据集中有负数据,则应该使用ushort而不是short。

int h = 64, w = 64; 
    short[] myRawImageData = new short[4096]; 
    for (int i = 0; i < 4096; i++){ 
     //this rolls over into negative numbers 
     myRawImageData[i] = (short) (i * 14); 
    } 

    // Create signed 16 bit data buffer, and compatible sample model 
    DataBuffer dataBuffer = new DataBufferUShort(myRawImageData, w * h); 
    SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_USHORT, w, h, 1, w, new int[] {0}); 

    // Create a raster from sample model and data buffer 
    WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBuffer, null); 

    // Create a 16 bit signed gray color model 
    ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY); 
    ColorModel colorModel = new ComponentColorModel(colorSpace, false, false, Transparency.OPAQUE, DataBuffer.TYPE_USHORT); 

    // Finally create the signed 16 bit image 
    BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null); 

    try (FileOutputStream fos = new FileOutputStream("/tmp/tst.png")) { 
     ImageIO.write(image, "png", fos);// <--- Here goes the exception 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 

这是假设您期望负值是色域较亮的一半。

+0

仍然适用于我,或许您的输入数据是问题。 –

+0

我的输入数据包含负数。你也是吗? – JobNick

+0

我在添加负数时出现错误。 –