3

I get the pixels from BufferedImage using the method getRGB(). The pixels are stored in array called data[]. After some manipulation on data array, I need to create a BufferedImage again so that I can pass it to a module which will display the modified image, from this data array, but I am stuck with it.

DNA
  • 42,007
  • 12
  • 107
  • 146
Saurabh
  • 121
  • 1
  • 2
  • 12

3 Answers3

26

I get the pixels from the BufferedImage using the method getRGB(). The pixels are stored in array called data[].

Note that this can possibly be terribly slow. If your BufferedImage supports it, you may want to instead access the underlying int[] and directly copy/read the pixels from there.

For example, to fastly copy your data[] into the underlying int[] of a new BufferedImage:

BufferedImage bi = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB );
final int[] a = ( (DataBufferInt) res.getRaster().getDataBuffer() ).getData();
System.arraycopy(data, 0, a, 0, data.length);

Of course you want to make sure that your data[] contains pixels in the same representation as your BufferedImage (ARGB in this example).

TacticalCoder
  • 6,275
  • 3
  • 31
  • 39
  • 1
    This is the better answer. I can't think of any situation in which setRGB is an optimal solution for anything. – man guy Oct 31 '17 at 07:48
  • 3
    I think there's a mistake in your code: do you mean `bi.getRaster` instead of `res.getRaster`? – RDM Jan 26 '18 at 16:16
  • @manguy I don't think their answer works, I tried it. I think it is because they made an array using the BufferedImage data, but the array doesn't actually point to the BufferedImage. It is just a new reference that was created. – Some Guy Jan 30 '22 at 02:27
0
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Then set the pixels again.

bufferedImage.setRGB(x, y, your_value);

PS: as stated in the comments, please use the answer from @TacticalCoder

epoch
  • 16,396
  • 4
  • 43
  • 71
-1

You can set the RGB (int) values for the pixels in the new image using the setRGB methods.

cdc
  • 2,511
  • 2
  • 17
  • 15