Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Painting pixels images in Java

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);
    }
}
like image 217
Tom1983 Avatar asked Aug 13 '11 00:08

Tom1983


3 Answers

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
like image 65
Perception Avatar answered Sep 17 '22 22:09

Perception


The key here is the Canvas class. It is the standard Component that allows arbitrary draw operations. In order to use it, you must subclass the Canvas class and override the paint(Graphics g) method, then loop through each pixel and draw your random color. The following code should work:

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

import javax.swing.JFrame;

public class PixelCanvas extends Canvas {
    private static final int WIDTH = 400;
    private static final int HEIGHT = 400;
    private static final Random random = new Random();

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        for(int x = 0; x < WIDTH; x++) {
            for(int y = 0; y < HEIGHT; y++) {
                g.setColor(randomColor());
                g.drawLine(x, y, x, y);
            }
        }
    }

    private Color randomColor() {
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setSize(WIDTH, HEIGHT);
        frame.add(new PixelCanvas());

        frame.setVisible(true);
    }
}

The generated image looks like this:

Noise Image

like image 20
kylc Avatar answered Sep 18 '22 22:09

kylc


You'll probably want to create a BufferedImage of the size you want, and use img.setRGB(x, y, getRandomColor()) to create a bunch of random pixels. Then you could render the whole image wherever you want it.

like image 30
cHao Avatar answered Sep 20 '22 22:09

cHao