如何使用BufferedImage对象创建1位位图?

时间:2015-03-15 16:23:10

标签: java bitmap

我试图获取 1位位图的RGB,将其放在多维数组中以执行某些任务并再次将位图重新创建为其原始形式。 虽然几乎相同的代码可以很好地处理4位和8位位图,但我的最终结果显示1位位图的黑色图像,不能确定我在这里做错了什么! 提前致谢。

BufferedImage in = ImageIO.read(new File("D:\\SourceImage.bmp"));
int w = in.getWidth(), h = in.getHeight();
int[][] array = new int[w][h];
for (int j = 0; j < w; j++) {
    for (int k = 0; k < h; k++) {
        array[j][k] = in.getRGB(j, k);
    }
}

// perform operations on array[ ][ ]

byte[] v = new byte[2];
for (int i = 0; i < v.length; ++i) {
    v[i] = (byte) (i );
}
ColorModel cm = new IndexColorModel(1, v.length, v, v, v);
WritableRaster wr = cm.createCompatibleWritableRaster(w, h);
BufferedImage out = new BufferedImage(cm, wr, false, null);
for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
        int Pixel = array[x][y] << 16 | array[x][y] << 8 | array[x][y];
        out.setRGB(x, y, array[x][y]);
    }
}
Graphics2D g = out.createGraphics();
g.drawImage(out, 0, 0, null);
g.dispose();
ImageIO.write(out, "bmp", new File("D:\\ResultImage.bmp"));

1 个答案:

答案 0 :(得分:1)

v的值必须为0和255,而不是0和1.否则,您将获得具有暗值RGB(0,0,0)和光值RGB(1, 1,1)看似全黑。

byte[] v = {(byte) 0, (byte) 0xff};