我想读取一个灰度图像文件,例如lena.bmp,然后在java中降低灰度分辨率,我是用来PixelGrabber
获取这个图像的像素数据的,如何将这个8位灰度位图转换为4位?谢谢!
问问题
2543 次
2 回答
3
不确定他们是否可以在这里为您提供帮助,但也许您可以看看JAI(Java Advanced Imaging)、Apache Commons Sanselan或Image4j。
编辑:
刚刚测试了 Image4J 库:
转换 8 Bit -> 4 Bit 非常简单:
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 文档。
于 2012-10-01T11:29:02.527 回答
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 = 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]));
}
于 2012-10-01T11:33:37.933 回答