创建自定义BufferedImage

时间:2011-03-06 00:35:10

标签: java image awt bufferedimage

我正在编写一个方法,它接受三个2D int数组(表示图像的R,G和B值),宽度和高度,以及表示指定图像是彩色还是黑白的布尔值。我想要的方法是从给定的输入数据创建一个BufferedImage。

这是我到目前为止所做的:

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 BufferedImage(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;
}

然而,我写了一个单元测试,应该创建一个5x5彩色图像,用白色(255,255,255)填充,但是栅格数据填充的是非常大的值,而不是255.我不太熟悉这个图像东西和AWT一般,所以我觉得我没有正确创建BufferedImage。我一直在尝试引用BufferedImage的Java API,但是没有太多运气搞清楚。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您的代码对我来说没问题。图像应填充0xffffff(R,G和B各为255),十进制为16777215。 (如果你有一个alpha通道,那么每个完全不透明的像素都是0xffffffff,十进制为-1。)