I've got a byte array corresponding to pixel values of data type unsigned short (written by a C++ application). I need to convert these values into a BufferedImage and display or save it.
I'm using the following loop:
int xsize=1024;
int ysize=1024;
for (int i = 0; i < bandCount; i++)
{
ints[i]=new int[pixels];
for(int j=0;j<pixels*2;j+=2)
{
short temp=bands[i].getShort(index);
ints[i][index]=(temp&0xffff);
index++;
}
}
imgBuffer = new DataBufferInt(ints, pixels);
buffer_type = DataBuffer.TYPE_INT;
sampleModel = new BandedSampleModel(buffer_type, xsize, ysize,
xsize, banks, offsets);
data_type = BufferedImage.TYPE_USHORT_GRAY;
}
WritableRaster raster = Raster.createWritableRaster(sampleModel,
imgBuffer, null);
BufferedImage img = new BufferedImage(xsize, ysize, data_type);
img.setData(raster);
Where pixels is simply the width*height of the image. bands[] is the ByteBuffer containing the pixel values. I read in the next short, AND it into an int value, and after the loop, create a DataBuffer of these int values. Then I try to create a BandedSampleModel from the converted pixel values. The DataBuffer type is INT (I think) and the BufferedImage is set to be USHORT_GRAY.
The image looks horrible- it's skipping every other pixel, I think. I've tried changing the BufferedImage type (data_type above), but there's no 32-bit grayscale option. I've tried using TYPE_INT_ARGB and gotten an exception stating that setData on the BufferedImage is using an out-of-bounds index(1024). The image is much larger than 1024x1024; I locked xsize and ysize to those values to reduce the amount of time spent producing an error.
I'm a bit out of my depth here; how can I create a BufferedImage using an array of unsigned short pixel values? Am I reading the pixel values incorrectly in the loop, or am I simply setting the DataBuffer or BufferedImage types incorrectly?
Thanks!
I'd use ImageJ
> Import
> Raw…
, which handles unsigned short correctly. It has a convenient macro facility, too.
Addendum: One convenience of using ImageJ
is that it maps the range of unsigned short values present in the input to an evenly-spaced palette of 256 RGB gray values. You can see the effect by importing a raw image and selecting Analyze
> Histogram
. Of course, you can apply any desired LUT using Image
> Lookup Tables
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.