我有由short[]
表示的原始灰度图像像素。我想从中创建BufferedImage
并将其另存为PNG。
由于TYPE_SHORT_GRAY
没有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 :(得分:0)
你的代码对我来说很好,我得到错误的唯一方法就是我改变了bandOffsets。你能给我们更多你的代码吗?
修改的 如果数据集中包含负数据,则应该使用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();
}
假设您认为负值是色域的较亮部分。