I am writing a Buddhabrot fractal generator using aparapi. I got the OpenCL part of it to work, resulting in a single-dimension array that represents each pixel. I have the dimensions of the final image as final ints, and have written code to get the index of arbitrary points in that array. I want to save this as an image and I'm trying to use BufferedImage with TYPE_USHORT_GRAY. Here's what I have so far:
BufferedImage image=new BufferedImage(VERTICAL_PIXELS, HORIZONTAL_PIXELS, BufferedImage.TYPE_USHORT_GRAY);
for(int i=0; i<VERTICAL_PIXELS; i++)
for(int k=0; k<HORIZONTAL_PIXELS; k++)
image.setRGB(k, i, normalized[getArrayIndex(k,i,HORIZONTAL_PIXELS)]);
The problem is, I don't know what to set the RGB as. What do I need to do?
For reference, this example shows how two different
BufferedImage
types interpret the same 16 bit data. You can mouse over the images to see the pixel values.Addendum: To elaborate on the word interpret, note that
setRGB()
tries to find the closest match to the specified value in the givenColorModel
.The problem here is that
setRGB()
wants an 0xRRGGBB color value. BufferedImage likes to pretend that the image is RGB, no matter what the data is stored as. You can actually get at the internalDataBufferShort
(withgetTile(0, 0).getDataBuffer()
), but it can be tricky to figure out how it is laid out.If you already have your pixels in a
short[]
, a simpler solution might be to copy them into anint[]
instead an jam it into aMemoryImageSource
:The advantage of this approach is that you control the underlying pixel array. You could make changes to that array and call
newPixels()
on yourMemoryImageSource
, and it would update live. It also gives you complete power to define your own palette other than grayscale:This approach works fine if you just want to display the image on the screen:
However, if you wanted to write it out to a file and preserve the one-short-per-pixel format (say, to load into Matlab) then you're out of luck. The best you can do is to paint it into a
BufferedImage
and save that withImageIO
, which will save as RGB.If you definitely need a
BufferedImage
at the end, another approach is to apply the color palette yourself, calculate the RGB values, and then copy them into the image: