0

I have some really simple code that's just not working:

int[] manualPixels = new int[width * height * 3];
for (int index = 0; index < manualPixels.length; index++) {
    if (index % 3 == 2) {
        manualPixels[index] = 255;
    }
}
BufferedImage pixelImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);    
pixelImage.setRGB(0, 0, width, height, manualPixels, 0, width);

ImageIO.write(pixelImage, "jpeg", tempFile);

This should, as far as I can determine, output a red, green, or blue image, depending upon whether 0, 1, or 2 is used in the if statement in the for loop. The problem is that instead of that, I invariably get blue and black stripes, no matter which pixels I set. For instance:

enter image description here

I'm sure there must be some basic thing that I'm doing wrong here, I'm just not seeing what it is. Any ideas?

aroth
  • 54,026
  • 20
  • 135
  • 176
  • "I have some really simple code that's just not working": story of my life –  May 30 '12 at 07:09
  • For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson May 30 '12 at 07:14
  • 1
    BTW - JPEG is an astonishing choice for the image type. Why not use PNG? – Andrew Thompson May 30 '12 at 07:15
  • 1
    @AndrewThompson - Because I want the output image size to be as small as possible, mostly. The solid color images are just for testing; in practice I will be creating images which generally do not compress much under a lossless algorithm like PNG. – aroth May 30 '12 at 07:40

1 Answers1

3

INT_RGB packs all the channels into the least significant three octets of an int. This means that you are setting every third pixel to blue, and the rest are left black. (This however doesn't match with your image - did you change the code after generating it?)

Try this instead:

int[] manualPixels = new int[width * height];
for (int index = 0; index < manualPixels.length; index++) {
    switch (index % 3) {
        case 0: manualPixels[index] = 0xFF0000; break; // red
        case 1: manualPixels[index] = 0x00FF00; break; // green
        case 2: manualPixels[index] = 0x0000FF; break; // blue
    }
}
Joni
  • 108,737
  • 14
  • 143
  • 193