因为项目要求,照片格式必须是像素为4bit(位深度4),借鉴了很多方法都不可以,发现原因是因为BufferedImage中缺少调色板参数,所以只能手动设置参数进行设置。
效果如下:
代码实现:
/**
* 转像素为4bit大小图片
* @param image 原图BufferedImage
* @param file 目标图生成路径
*/
public static void changeToFourPhoto(BufferedImage image,String file){
int width = image.getWidth();
int height = image.getHeight();
//手动设置调色板参数
final int img_bits = 4;
final byte[] colorTable_16 = {
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x80, (byte) 0x00,
(byte) 0x00, (byte) 0x80, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x80, (byte) 0x80, (byte) 0x00,
(byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x80, (byte) 0x00, (byte) 0x80, (byte) 0x00,
(byte) 0x80, (byte) 0x80, (byte) 0x00, (byte) 0x00,
(byte) 0x80, (byte) 0x80, (byte) 0x80, (byte) 0x00,
(byte) 0xc0, (byte) 0xc0, (byte) 0xc0, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0x00,
(byte) 0x00, (byte) 0xff, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0x00,
(byte) 0xff, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0xff, (byte) 0x00, (byte) 0xff, (byte) 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0x00, (byte) 0x00,
(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00
};
final IndexColorModel color_model = new IndexColorModel(img_bits
, colorTable_16.length / img_bits, colorTable_16
, 0, true);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY, color_model);
Graphics2D grap=img.createGraphics();
grap.drawImage(image, 0, 0, width, height, null);
grap.dispose();
File newFile = new File(file);
try {
//写出新图
ImageIO.write(img, "bmp", newFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}