为什么我的去除这种颜色的方法不起作用?

Why isn't my method for removing this color working?

我正在尝试制作马里奥游戏克隆,现在,在我的构造函数中,我有一个方法应该使某种颜色透明而不是当前的粉红色(R:255,G:0 ,乙:254)。根据 Photoshop,十六进制值为 ff00fe。我的方法是:

public Mario(){
    this.state = MarioState.SMALL;
    this.x = 54;
    this.y = 806;
    URL spriteAtLoc = getClass().getResource("sprites/Mario/SmallStandFaceRight.bmp");

    try{
      sprite = ImageIO.read(spriteAtLoc);
      int width = sprite.getWidth();
      int height = sprite.getHeight();
      int[] pixels = new int[width * height];
      sprite.getRGB(0, 0, width, height, pixels, 0, width);

      for (int i = 0; i < pixels.length; i++) {

        if (pixels[i] == 0xFFff00fe) {

          pixels[i] = 0x00ff00fe; //this is supposed to set alpha value to 0 and make the target color transparent
        }

      }
    } catch(IOException e){
      System.out.println("sprite not found");
      e.printStackTrace();
    }
  }

它运行并编译,但当我渲染它时,精灵出现完全一样。 (编辑:也许值得注意的是,我的 paintComponent(g) 方法中没有 super.paintComponent(g)。精灵是 .bmps。

您仅使用 BufferedImage.getRGB 检索像素。即returns对BufferedImage某个区域的数据进行复制

您对返回的 int[] 所做的任何更改都不会自动反映回图像中。

要更新图像,您需要在更改 int[]:

后调用 BufferedImage.setRGB
sprite.setRGB(0, 0, width, height, pixels, 0, width);

你可能应该做的另一个改变(这涉及到一些猜测,因为我没有你的 bmp 来测试) - ImageIO.read 返回的 BufferedImage 可能有类型 BufferedImage.TYPE_INT_RGB - 意思它没有 alpha 通道。您可以通过打印 sprite.getType() 来验证,如果打印 1 它是没有 alpha 通道的 TYPE_INT_RGB。

要获得 alpha 通道,请创建一个大小合适的新 BufferedImage,然后在该图像上设置转换后的 int[],然后从那时起使用新图像:

BufferedImage newSprite = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
newSprite.setRGB(0, 0, width, height, pixels, 0, width);
sprite = newSprite; // Swap the old sprite for the new one with an alpha channel

BMP 图像不提供 alpha 通道,您必须手动设置它(就像您在代码中所做的那样)...

当您检查您的像素是否具有特定颜色时,您必须在没有 alpha 的情况下进行检查(BMP 没有 alpha,它始终为 0x0)。

if (pixels[i] == 0x00ff00fe) { //THIS is the color WITHOUT alpha
    pixels[i] = 0xFFff00fe; //set alpha to 0xFF to make this pixel transparent
}

简而言之:你做的很好,但有点混乱^^

这个有效:

private BufferedImage switchColors(BufferedImage img) {
    int w = img.getWidth();
    int h = img.getHeight();
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    // top left pixel is presumed to be BG color
    int rgb = img.getRGB(0, 0); 
    for (int xx=0; xx<w; xx++) {
        for (int yy=0; yy<h; yy++) {
            int rgb2 = img.getRGB(xx, yy);
            if (rgb2!=rgb) {
                bi.setRGB(xx, yy, rgb2);
            }
        }
    }

    return bi;
}