这确实将位数减少到 4:
public static void main(String[] args) throws Exception {
BufferedImage in = ImageIO.read(new File(args[0]));
int w = in.getWidth(), h = in.getHeight();
int[] bits = { 4 };
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
int dt = DataBuffer.TYPE_BYTE;
ColorModel cm = new ComponentColorModel
(cs, bits, false, false, Transparency.OPAQUE, dt);
WritableRaster wr = cm.createCompatibleWritableRaster(w, h);
BufferedImage out = new BufferedImage(cm, wr, false, null);
Graphics2D g = out.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();
ImageIO.write(out, "png", new File(args[1]));
}
在我迄今为止尝试过的所有查看器应用程序中,生成的文件都会显得太暗。但是如果您只对位感兴趣,那么在上述转换之后对wr 栅格进行操作可能对您来说已经足够了。
如果没有,那么也许您应该设置一个IndexedColorModel,其中包含您想要的 24 个灰度级。您可以简单地将索引乘以 17 以获得均匀分布的强度,从 0x0 * 17 = 0x00 到 0xf * 17 = 0xff。
public static void main(String[] args) throws Exception {
BufferedImage in = ImageIO.read(new File(args[0]));
int w = in.getWidth(), h = in.getHeight();
byte[] v = new byte[1 << 4];
for (int i = 0; i < v.length; ++i)
v[i] = (byte)(i*17);
ColorModel cm = new IndexColorModel(4, v.length, v, v, v);
WritableRaster wr = cm.createCompatibleWritableRaster(w, h);
BufferedImage out = new BufferedImage(cm, wr, false, null);
Graphics2D g = out.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();
ImageIO.write(out, "png", new File(args[1]));
}