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

3

我正在尝试获取一个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个回答

2
你需要将 v 的值设为 0 和 255,而非 0 和 1。否则,你得到的图像中暗色部分会是 RGB(0, 0, 0),亮色部分会是 RGB(1, 1, 1),看起来整张图片都是黑色的。请注意保留 HTML 标签。
byte[] v = {(byte) 0, (byte) 0xff};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接