【问题标题】:How can i find out where a BufferedImage has Alpha in Java?如何找出 BufferedImage 在 Java 中的 Alpha 位置?
【发布时间】:2012-05-02 18:47:24
【问题描述】:

我有一个 BufferredImage 和一个 boolean[][] 数组。 我想在图像完全透明的情况下将数组设置为 true。

类似:

for(int x = 0; x < width; x++) {
    for(int y = 0; y < height; y++) {
        alphaArray[x][y] = bufferedImage.getAlpha(x, y) == 0;
    }
}

但是 getAlpha(x, y) 方法不存在,我没有找到其他可以使用的方法。 有一个 getRGB(x, y) 方法,但我不确定它是否包含 alpha 值或如何提取它。

谁能帮帮我? 谢谢!

【问题讨论】:

标签: java graphics alpha bufferedimage


【解决方案1】:
public static boolean isAlpha(BufferedImage image, int x, int y)
{
    return image.getRBG(x, y) & 0xFF000000 == 0xFF000000;
}
for(int x = 0; x < width; x++)
{
    for(int y = 0; y < height; y++)
    {
        alphaArray[x][y] = isAlpha(bufferedImage, x, y);
    }
}

【讨论】:

  • 这是干净高效的,但是这个函数的逻辑是倒退的。根据Color 上的 javadoc,“alpha 值为 1.0 或 255 表示颜色完全不透明,alpha 值为 0 或 0.0 表示颜色完全透明。”如果 alpha 位为 255,则此函数返回 true,这意味着像素是不透明的。
  • 看起来像是错字:getRBG需要根据docs.oracle.com/javase/7/docs/api/java/awt/image/…替换为getRGB
【解决方案2】:

试试这个:

    Raster raster = bufferedImage.getAlphaRaster();
    if (raster != null) {
        int[] alphaPixel = new int[raster.getNumBands()];
        for (int x = 0; x < raster.getWidth(); x++) {
            for (int y = 0; y < raster.getHeight(); y++) {
                raster.getPixel(x, y, alphaPixel);
                alphaArray[x][y] = alphaPixel[0] == 0x00;
            }
        }
    }

【讨论】:

    【解决方案3】:
    public boolean isAlpha(BufferedImage image, int x, int y) {
        Color pixel = new Color(image.getRGB(x, y), true);
        return pixel.getAlpha() > 0; //or "== 255" if you prefer
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多