2017-05-28 81 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

我在添加負數時出現錯誤。 –