3

I'm having a really bad time dealing with RGB values in Java, which made me start trying small experiments with this.

I came down to this: loading an image, get it's rgb values and creating a new image with the same values. Unfortunately, this does not work (the images are displayed differently, see picture), as per the following code... Can some one see what's wrong?

BufferedImage oriImage=ImageIO.read(new  URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));

int[] oriImageAsIntArray = new int[oriImage.getWidth()*oriImage.getHeight()];
oriImage.getRGB(0, 0, oriImage.getWidth(),oriImage.getHeight(), oriImageAsIntArray, 0, 1);

BufferedImage bfImage= new BufferedImage(oriImage.getWidth(),oriImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);

bfImage.setRGB(0,0,bfImage.getWidth(),bfImage.getHeight(),oriImageAsIntArray, 0, 1);

output

Vespas
  • 385
  • 1
  • 3
  • 11

1 Answers1

6

Apparently, getRGB and setRGB were not being used correctly.

I changed the code to:

oriImage.getRGB(0, 0, oriImage.getWidth(),oriImage.getHeight(), oriImageAsIntArray, 0,  oriImage.getWidth());
(...)
bfImage.setRGB(0,0,bfImage.getWidth(),bfImage.getHeight(),oriImageAsIntArray, 0, bfImage.getWidth());

... and the picture displayed correctly. I still do not understand what this last argument is. In the JavaDoc, it is described as:

scansize - scanline stride for the rgbArray
Vespas
  • 385
  • 1
  • 3
  • 11
  • It looks like the last argument is the width of the image, so that the method knows when to start each new row. – Tharwen Mar 01 '14 at 18:26
  • Hmm, not sure: the width is already sent as third argument... And image width had already been set in the constructor... – Vespas Mar 01 '14 at 22:45
  • 14
    It's the length of the scan line. :-) In most cases, this is equal to the width, but it can also be larger. For some displays/image formats it may make sense to place padding at the end of each scan line (as an example, to make sure that each new line starts on an even number, ie. next word/longword boundary). These padding pixels does not make the image wider, but is still part of the backing data buffer/array, that's why you need this argument. As long as you use a value >= image width, and use the same value in both places, you should be good. Makes sense? :-) – Harald K Mar 01 '14 at 23:00