【问题标题】:How to generate the image with grayscale and different bitdepth in java?如何在java中生成具有灰度和不同位深度的图像?
【发布时间】:2015-10-27 12:19:36
【问题描述】:

我正在尝试实现一些 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 的位深。

有什么建议吗?

【问题讨论】:

    标签: java png bit-depth


    【解决方案1】:

    我尝试使用这种方式,似乎可行。

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

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2010-10-03
      • 2021-01-13
      • 2021-11-20
      • 2021-12-23
      相关资源
      最近更新 更多