【问题标题】:Get 0-255 values from DataBufferByte.getData for each color从 DataBufferByte.getData 中为每种颜色获取 0-255 个值
【发布时间】:2013-03-29 11:38:29
【问题描述】:

我正在尝试使用以下代码分析像素

    BufferedImage image;
    try {
        image = ImageIO.read(new File(fileName));
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    final byte[] pixels = ((DataBufferByte)         
    image.getRaster().getDataBuffer()).getData();final int pixelLength = 4;
        for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
            byte alpha = pixels[pixel];
            byte blue = pixels[pixel + 1];
            byte green = pixels[pixel + 2];
            byte red = pixels[pixel + 3];
            //analyze colors
            col++;
            if (col == width) {
                col = 0;
                row++;
            }
        }

我有一个最简单的例子,我有一个有两个像素的图像,一个有透明度,一个没有。

像素 1:透明的红色

HEX: FF0000, Alpha 140, (RGB: 255, 0, 0)

像素 2:没有透明度的绿松石色

HEX: 7FFFD8, Aplha  255, (RGB: 127, 255, 216)

上面的像素数组有以下值:[-116, 0, 0, -1, -1, -40, -1, 127] 其中每个像素有四个字节,顺序为 a、b、g、r(我认为)。

所以我的问题是,我如何从上面的结果中得到我使用的 0-255 值:)

【问题讨论】:

  • 字节结构是无符号的,因此如果您将值读入其中(如您发布的示例中所示),值将在 0..255 范围内。确保每个子像素确实是一个字节,而不是 2B 或浮点数。您的打印输出可能有误。

标签: java image-processing bytearray


【解决方案1】:

我不确定我是否理解了这个问题……但根据我的理解,这里是一个简单的答案。

无需讨论two's complement,您可以遍历整个数组并使用以下规则对其进行转换:

  • 如果值小于零,加256
  • 如果值为零或更大,则保持原样

这有帮助吗?

【讨论】:

  • 是的,这有帮助,但我需要将类型更改为字节以外的其他内容,因为 (byte)-1 + 256 = -1
  • 对不起,我应该告诉你使用 int。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 2014-09-14
  • 1970-01-01
  • 2021-06-06
  • 2011-11-29
  • 2014-03-21
  • 2015-01-27
相关资源
最近更新 更多