I'm trying to color individual pixels in a BufferedImage
(TYPE_INT_RGB) using setRGB()
, but I'm not sure how to format the RGB values. I want the result as a single integer. Is there a method that will take three int
values (red, green, blue) and return a correctly formatted integer for setRGB()
?
views:
28answers:
2+1, clear and simple.
The Elite Gentleman
2010-04-03 20:58:25
+2
A:
Assuming you have ints r
, g
, and b
, you can do:
int pixel = (r << 16) | (g << 8) | b;
This is because pixels in a BufferedImage
are 4-byte ints. The 4-bytes represent Alpha, Red, Green, and Blue, in that order. So, if you shift red left by two bytes and green left by one byte, then bitwise-or r
, g
, and b
, you will get a valid pixel to use with setRGB()
.
Justin Ardini
2010-04-03 20:59:39
The answer provided below shows a deeper knowledge of the Java APIs, but I gave +1 here because with this answer you'll find your way around almost any graphics/image processing library
Fabio de Miranda
2010-04-04 01:55:50