The problem is that setRGB() requires a color value of 0xRRGGBB. BufferedImage loves pretending to be an RGB image, no matter what data is stored. In fact, you can get the internal DataBufferShort (with getTile(0, 0).getDataBuffer() ), but it can be difficult to determine how it is laid out.
If you already have pixels in short[] , a simpler solution would be to copy them to int[] instead of shooting it in a MemoryImageSource :
int[] buffer = ; ColorModel model = new ComponentColorModel( ColorSpace.getInstance(ColorSpace.CS_GRAY), new int[] { 16 }, false, true, Transparency.OPAQUE, DataBuffer.TYPE_USHORT); Image image = Toolkit.getDefaultToolkit().createImage( new MemoryImageSource(VERTICAL_PIXELS, HORIZONTAL_PIXELS, model, buffer, 0, VERTICAL_PIXELS));
The advantage of this approach is that you control the underlying array of pixels. You can make changes to this array and call newPixels() on your MemoryImageSource , and it will be updated in real time. It also gives you full power to define your own palette, except for shades of gray:
int[] cmap = new int[65536]; for(int i = 0; i < 65536; ++i) { cmap[i] = (((i % 10000) * 256 / 10000) << 16) | (((i % 20000) * 256 / 20000) << 8) | (((i % 40000) * 256 / 40000) << 0); } ColorModel model = new IndexColorModel(16, 65536, cmap, 0, false, -1, DataBuffer.TYPE_USHORT);
This approach works fine if you just want to display the image on the screen:
JFrame frame = new JFrame(); frame.getContentPane().add(new JLabel(new ImageIcon(image))); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);
However, if you want to write it to a file and save the format with one short pixel (say, upload to Matlab), you're out of luck. The best you can do is draw it in a BufferedImage and save it using ImageIO , which will be saved 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 to the image:
short[] data = ; int[] cmap = ; int[] rgb = new int[data.length]; for(int i = i; i < rgb.length; ++i) { rgb[i] = cmap[data[i]]; } BufferedImage image = new BufferedImage( VERTICAL_PIXELS, HORIZONTAL_PIXELS, BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, VERTICAL_PIXELS, HORIZONTAL_PIXELS, pixels, 0, VERTICAL_PIXELS);