【问题标题】:Two similar methods with BufferedImage, one working, one not. Why?两种与 BufferedImage 类似的方法,一种有效,一种无效。为什么?
【发布时间】:2012-03-05 05:12:44
【问题描述】:

我试图制作一种方法,将 BufferedImage 的一种颜色更改为不可见。
我自己找不到解决方案,所以我请求您的帮助。
这是我自己做的方法:

public static BufferedImage makeWithoutColor(BufferedImage img, Color col)
{
    BufferedImage img1 = img;
    BufferedImage img2 = new BufferedImage(img1.getWidth(), img1.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = img2.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.drawImage(img1, null, 0, 0);
    g.dispose();
    for(int i = 0; i < img2.getWidth(); i++)
    {
        for(int j = 0; i < img2.getHeight(); i++)
        {
            if(img2.getRGB(i, j) == col.getRGB())
            {
                img2.setRGB(i, j, 0x8F1C1C);
            }
        }
    }
    return img2;
}

这是我阅读的教程中的一个。

public static BufferedImage makeColorTransparent(BufferedImage ref, Color color) {
    BufferedImage image = ref;
    BufferedImage dimg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = dimg.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.drawImage(image, null, 0, 0);
    g.dispose();
    for(int i = 0; i < dimg.getHeight(); i++) {
        for(int j = 0; j < dimg.getWidth(); j++) {
            if(dimg.getRGB(j, i) == color.getRGB()) {
            dimg.setRGB(j, i, 0x8F1C1C);
            }
        }
    }
    return dimg;
}

【问题讨论】:

  • 您有错误信息吗?您是否尝试过复制/粘贴教程并将image 更改为img1
  • 好的,哪一个有效,哪一个无效?如果一个人正在工作,那是什么问题/
  • 高度/宽度倒序,有问题吗?
  • 不,当我绘制这张图片时,它看起来就像什么都没做,第二个也在工作。

标签: java bufferedimage


【解决方案1】:

我假设“不可见”是指您想让一种颜色透明。使用这种方法您将无法做到这一点,因为setRGB 不会影响 Alpha 通道。你最好使用图像过滤器。这是来自this thread的一种方法:

public static Image makeWithoutColor(BufferedImage img, Color col)
{
    ImageFilter filter = new RGBImageFilter() {

        // the color we are looking for... Alpha bits are set to opaque
        public int markerRGB = col.getRGB() | 0xFF000000;

        public final int filterRGB(int x, int y, int rgb) {
            if ((rgb | 0xFF000000) == markerRGB) {
                // Mark the alpha bits as zero - transparent
                return 0x00FFFFFF & rgb;
            } else {
                // nothing to do
                return rgb;
            }
        }
    };
    ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
}

这会将具有指示 RGB 颜色和任何透明度的任何像素转换为相同颜色的完全透明像素。

【讨论】:

    【解决方案2】:

    你的错误是这一行:

    for(int j = 0; i < img2.getHeight(); i++)
    

    应该是:

    for(int j = 0; j < img2.getHeight(); j++)
    //             ^                     ^ as Ted mentioned...
    

    【讨论】:

    • 应该也应该是j++
    • 谢谢,可惜没看到。
    猜你喜欢
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多