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.
Asked
Active
Viewed 1.8k times
3
3 Answers
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
-
1This 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
-
3I 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
-
2You shouldn't loop through a whole image and set one bit at a time. You should copy the whole buffer in one go. – Yochai Timmer Dec 09 '14 at 11:50
-
2this is a terrible way to set all the pixels in a bufferedimage and should not be the accepted answer. – user_4685247 Oct 29 '15 at 17:48
-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