3

I want to manipulate an image on a pixel by pixel basis in Java so I have set up a one dimensional list with my colours in it. I then convert this to a buffered image, but the pixels were all wrong.

So I've stripped it down to the absolute basics below. To my mind this ought to give a square with the left half blue and the right have black. Instead it gives blue and black diagonal stripes. Any ideas about what is going on please?

   private void create(){
        int w = 100;
        int h = 100;
        int blue;
        int[] pix = new int[w * h];
        int index = 0;
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
              if (x<50) {blue = 255;} 
              else blue=0;
              pix[index++] =  blue;
            }
        }
       image = new BufferedImage(100,100, BufferedImage.TYPE_INT_RGB);
       image.setRGB(0, 0, 100, 100, pix, 0, 1);
  • Check this, maybe it will help you: http://stackoverflow.com/questions/9396159/how-do-i-create-a-bufferedimage-from-array-containing-pixels – m.aibin Dec 02 '15 at 17:53

1 Answers1

0

You got the stride variable wrong. This line:

image.setRGB(0, 0, 100, 100, pix, 0, 1);

Needs to be changed to:

image.setRGB(0, 0, 100, 100, pix, 0, 100);

There are a few small changes that could improve readability, but you can deal with those. The change above will fix the problem you asked about.

Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64