ComponentColorModel and MemoryImageSource

B

briberyjoust

Hi,

I am trying to do some image visualization with Java. My idea is to use
a MemoryImageSource and feed it with data from a byte array. For each
pixel, the byte array has 3 values following each other (one for red,
green and blue). To define this mapping, I have defined a
ComponentColorModel.

The problem is: nothing is shown (only background). For my example
below, I would expect a red square (red=0xff, green=0, blue=0).

Thanks for any advice!

Regards,
Paul

-------8<-------------------------------------

package spiel;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Transparency;

import java.awt.Image;

import java.awt.color.ColorSpace;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.MemoryImageSource;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Example extends JPanel {
private final Image image;
private final int width = 800, height = 600;

public Example() {
super ();

// create raw data
byte[] pixbuf = new byte[width * height * 3];
for (int i = 0; i < pixbuf.length; i += 3) {
pixbuf[i + 0] = -128; // red maximum
pixbuf[i + 1] = 0;
pixbuf[i + 2] = 0;
}

// ColorModel (no alpha channel!)
ColorModel colorModel = new ComponentColorModel(
ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] {8, 8,
8},
false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);

// create image out of ColorModel and raw data.
MemoryImageSource imageSource
= new MemoryImageSource(width, height, colorModel, pixbuf, 0,
width * 3);
image = createImage(imageSource);

}

public void paintChildren(Graphics g) {
super.paintChildren(g);
g.drawImage(image, 0, 0, width, height, this);
}

public Dimension getPreferredSize() {
return new Dimension(width, height);
}

public static void main(String[] args) {
JFrame frame = new JFrame("View");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Example());
frame.pack();
frame.setVisible(true);
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,701
Latest member
XavierQ83

Latest Threads

Top