Creating a custom BufferedImage
I'm writing a method that takes three 2D int arrays (representing R, G, and B values of an image), a width and height, and a boolean denoting if the specified image is color or black and white. What I want the method to do is create a BufferedImage from the given input data.
Here is what I have so far:
public static BufferedImage createImage(int[][] r, int[][] g, int[][] b,
int width, int height, boolean isColor) {
BufferedImage ret;
if (isColor)
ret = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
else
ret = new BufferedImag开发者_JAVA百科e(width, height, BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = ret.getRaster();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (isColor) {
raster.setSample(j, i, 0, r[i][j]);
raster.setSample(j, i, 1, g[i][j]);
raster.setSample(j, i, 2, b[i][j]);
}
else
raster.setSample(j, i, 0, r[i][j]);
}
}
return ret;
}
However, I wrote a unit test which should create a 5x5 colored image filled with white (255, 255, 255), but the raster data is filled with extremely large values and not 255. I'm not too familiar with this image stuff and AWT in general, so I feel like I'm not creating the BufferedImage correctly. I've been trying to reference the Java API for BufferedImage, but haven't had much luck figuring it out. Any help would be appreciated.
Your code looks ok to me. The image should be filled with 0xffffff (255 in each of R, G, and B), which will be 16777215 in decimal. (If you had an alpha channel, then each fully opaque pixel would be 0xffffffff, which would be -1 in decimal.)
精彩评论