Painting pixels images in Java

Tom1983 picture Tom1983 · Aug 13, 2011 · Viewed 25.8k times · Source

Which method is the best way to create a pixel image with java. Say, I want to create a pixel image with the dimensions 200x200 which are 40.000 pixels in total. How can I create a pixel from a random color and render it at a given position on a JFrame.

I tried to create a own component which just creates pixel but it seems that this is not very performant if I create such a pixel a 250.000 times with a for-loop and add each instance to a JPanels layout.

class Pixel extends JComponent {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(getRandomColor());
        g.fillRect(0, 0, 1, 1);
    }
}

Answer

Perception picture Perception · Aug 13, 2011

You do not need to create a class for this. Java already has the excellent BufferedImage class that does exactly what you need. Here is some pseudo-code:

int w = 10;
int h = 10;
int type = BufferedImage.TYPE_INT_ARGB;

BufferedImage image = new BufferedImage(w, h, type);

int color = 255; // RGBA value, each component in a byte

for(int x = 0; x < w; x++) {
    for(int y = 0; y < h; y++) {
        image.setRGB(x, y, color);
    }
}

// Do something with image