2012-02-13 55 views
0

我试图使方法将BufferedImage的一种颜色更改为不可见。
我自己找不到解决方案,所以请求您的帮助。
这里是方法我做的:两个类似的方法与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; 
} 
+0

您是否有错误信息?你有没有尝试复制/粘贴教程,只是将'image'改为'img1'? – talnicolas 2012-02-13 19:30:29

+1

好的,哪个人在工作,哪个不在?如果有人正在工作什么问题/ – ghostbust555 2012-02-13 19:30:47

+0

高度/宽度倒序,这可能是问题吗? – kosa 2012-02-13 19:30:51

回答

2

你的错误是这行:

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

应该是:

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

也许应该是'j ++'。 – 2012-02-13 19:32:24

+0

@TedHopp facepalming我自己 – MByD 2012-02-13 19:32:45

+0

谢谢,多么可惜,我没有看到它。 – Boblob 2012-02-13 19:33:10

0

我认为通过 “看不见” 你的意思是你想使一个颜色透明。你不能使用这种方法做到这一点,因为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颜色和任何透明度相同颜色的完全透明像素。

相关问题