繁体   English   中英

为什么我的消除这种颜色的方法无效?

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

我正在尝试制作Mario游戏克隆,现在,在我的构造函数中,我有一种方法应该使某种颜色透明而不是当前的粉红色(R:255,G:0,B: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检索像素。 这将返回BufferedImage特定区域中的数据副本

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

要更新图像,您需要在更改int[]之后调用BufferedImage.setRGB

sprite.setRGB(0, 0, width, height, pixels, 0, width);

另一个变化你应该做(这涉及到一个小猜测,因为我没有你的BMP来测试) -返回的BufferedImage的ImageIO.read可能有型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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM