如何在java中将8位灰度位图转换为4位?

时间:2012-10-01 09:50:44

标签: java bitmap

我想读取灰度图像文件,例如lena.bmp,然后降低java中的灰度级分辨率,我使用PixelGrabber来获取此图像的像素数据,如何转换此8位灰度位图到4位? 谢谢!

2 个答案:

答案 0 :(得分:2)

如果他们可以在这里帮助你,那就不舒服了,但也许你可以看看JAI (Java Advanced Imaging)Apache Commons SanselanImage4j

修改

刚刚测试了Image4J库:

转换8位 - > 4位非常简单:

final File inFile = new File("test.bmp");
final File outFile = new File("test2.bmp");

BufferedImage inImage = ImageIO.read(inFile);
BufferedImage outImage = ConvertUtil.convert4(inImage); // Converts to 4 Bit

ImageIO.write(outImage, "bmp", outFile);

有关更多信息,请参阅Image4J - ConvertUtil Documentation

答案 1 :(得分:1)

这确实将位数减少到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,其中包含您想要的2 4 灰度级。您可以简单地将索引乘以17,以获得从0x0 * 17 = 0x000xf * 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]));
}