1

我正在尝试实现一些java代码,可以帮助根据PNG图像的某些特征调整PNG图像:例如颜色允许解释类型位深度

0 1,2,4,8,16 每个像素都是一个灰度样本。

从中我搜索到如果颜色类型为0,我应该根据不同的位深度来实现代码:1、2、4、8、16,用于灰度。

我想使用 Graphic2D 库,所以我认为:

 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 的位深。

有什么建议吗?

4

1 回答 1

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);

谢谢。

于 2015-08-04T22:46:26.053 回答