Objects of the BufferedImage class represent images that we can draw to.
BufferedImage myImage = new BufferedImage(myWidth,
myHeight,
BufferedImage.TYPE_INT_ARGB)
where myWidth is the width in pixels (number of columns), myHeight is the height in pixels (number of rows), and the last argument specifies that each pixel has its own a red, green, blue, and transparency (alpha) value.
int ncols = myImage.getWidth(); int nrows = myImage.getHeight();
myImage.getRGB(ix,iy)where ix is the x-coordinate (column number), and iy is the y-coordinate (row number).
Recall that (0,0) is the upper-left corner, that increasing x values move you rightward, and that increasing y values move you downward.
The value you get back will be an int. It encodes 8 bits of alpha (0 = completely transparent, 255 = completely opaque), 8 bits of red (0 = no red, 255 = maximum redness), 8 bits of green (0 = no green, 255 = maximum greeness), and 8 bits of blue (0 = no blue, 255 = maximum blueness). You can extract the individual components from the int returned by getRGB as follows:
int rgb = myImage.getRGB(ix, iy); int alpha = (rgb & 0xFF000000) >>> 24; int red = (rgb & 0x00FF0000) >>> 16; int green = (rgb & 0x0000FF00) >>> 8; int blue = (rgb & 0x000000FF) >>> 0;
myImage.setRGB(ix, iy, rgb)where ix and iy are the column and row numbers, and rgb is an integer encoding a particular red-green-blue-alpha value.
If you want to just copy an existing pixel from one image to another, you can say
destImage.setRGB(destx, desty,
srcImage.getRGB(srcx, srcy));
Alternatively, you can create brand-new rgb values for setRGB by combining individual color components as follows:
int rgb = (alpha << 24) | (red << 16) | (green << 8) | blue;
Here is a code fragment that takes an existing image myImage, and creates a new image redderImage containing the same picture but with maximal red and maximal opaqueness.
BufferedImage redderImage = new BufferedImage(myImage.getWidth(),
myImage.getHeight(),
BufferedImage.TYPE_INT_ARGB);
for (int ix = 0; ix < myImage.getWidth(); ++ix) {
for (int iy = 0; iy < myImage.getHeight(); ++iy) {
int rgb = myImage.getRGB(ix,iy);
int new_alpha = 255; // Maximum!
int new_red = 255; // Maximum!
int new_green = (rgb & 0x0000FF00) >>> 8; // Copy original greenness
int new_blue = (rgb & 0x000000FF) >>> 0; // Copy original blueness
int new_rgb = (new_alpha << 24) | (new_red << 16) | (new_green << 8) | new_blue;
redderImage.setRGB(ix, iy, new_rgb);
}
}