Reputation: 21
I am trying to implement some java code that can help to adjust the PNG image based on some characteristics of PNG image: e.g. Color Allowed Interpretation Type Bit Depths
0 1,2,4,8,16 Each pixel is a grayscale sample.
From which I searched that if the color type is 0, I should implement the code based on the different bit depth: 1, 2, 4, 8, 16, for the grayscale.
I want to use the Graphic2D lib, so I think:
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();
But I don't know how to set the bit dipth for 2 and 4 with the image type "TYPE_BYTE_BINARY".
Any suggestion?
Upvotes: 2
Views: 833
Reputation: 21
I try to use this way, it seems work.
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);
Thanks.
Upvotes: 0