我正在尝试实现一些可以帮助根据PNG图像的某些特征调整PNG图像的java代码: 例如 颜色允许解释 键入位深度
0 1,2,4,8,16每个像素都是灰度样本。
我从中搜索过,如果颜色类型为0,我应该根据不同的位深度实现代码:1,2,4,8,16,用于灰度。
我想使用Graphic2D lib,所以我想:
if (img_bitDepth == 16) {
type = BufferedImage.TYPE_USHORT_GRAY; // 11
} else if (img_bitDepth == 8) {
type = BufferedImage.TYPE_BYTE_GRAY; //10
} else if (img_bitDepth == 4) {
type = BufferedImage.TYPE_BYTE_BINARY;
} else if (img_bitDepth == 2) {
type = BufferedImage.TYPE_BYTE_BINARY;
} else if (img_bitDepth == 1) {
type = BufferedImage.TYPE_BYTE_BINARY;
} else {
//logger warning.
}
BufferedImage resizedImage = new BufferedImage (img_width, img_height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, img_width, img_height, null);
g.dispose();
但我不知道如何使用图像类型" TYPE_BYTE_BINARY"来设置2和4的位深度。
有什么建议吗?
答案 0 :(得分:0)
我尝试使用这种方式,似乎有用。
private static final IndexColorModel createGreyscaleModel(int bitDepth) {
// Only support these bitDepth(1, 2, 4) for now: Set the size.
int size = 0;
if (bitDepth == 1 || bitDepth == 2 || bitDepth == 4) {
size = (int) Math.pow(2, bitDepth);
} else {
//logger error
return null;
}
// generate the rgb and set the greyscale color.
byte[] r = new byte[size];
byte[] g = new byte[size];
byte[] b = new byte[size];
// The size should be larger or equal to 2, so we firstly set the start and end pixel color.
r[0] = g[0] = b[0] = 0;
r[size-1] = g[size-1] = b[size-1] = (byte)255;
for (int i=1; i<size-1; i++) {
r[i] = g[i] = b[i] = (byte)((255/(size-1))*i);
}
return new IndexColorModel(bitDepth, size, r, g, b);
}
type = BufferedImage.TYPE_BYTE_BINARY;
IndexColorModel cm = createGreyscaleModel(img_bitDepth);
resizedImage = new BufferedImage (img_width, img_height, type, cm);
感谢。