2009-12-11 39 views
1

看着一個類似的問題,這個以前的迴應,我開發了這個代碼:嘗試設置透明度導入BMP圖像

public static BufferedImage getImage(String imagefile) { 

    BufferedImage image = null; 

    try { 

     image = javax.imageio.ImageIO.read(new java.io.File(imagefile));  

     int trans = image.getRGB(0,0); 
     final int width = image.getWidth(); 
     int[] imgData = new int[width]; 

     for (int y = 0; y < image.getHeight(); y++) { 
      // fetch a line of data from each image 
      image.getRGB(0, y, width, 1, imgData, 0, 1); 

      for (int x = 0; x < width; x++) 
       if (imgData[x] == trans) 
        imgData[x] |= 0xFF000000; 

      // replace the data 
      image.setRGB(0, y, width, 1, imgData, 0, 1); 
     }   

    } catch (Exception e) { 

      e.printStackTrace(); 

    } 

    return image; 

} 

在這裏面,這個想法是採取左上方的顏色和在與圖像中的顏色匹配的所有像素上應用透明度。 問題是,當我做

g.drawImage(img, across, down, cells, cells, null); 

我仍然可以被假設爲透明的顏色。我忘了一步嗎?

我用一個bmp文件來做測試。

謝謝你的時間。

回答

1

當我使用一個BufferedImage alpha值創建使用圖像:

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 

因此,也許你需要複製/轉換所有的像素是知道的阿爾法值的形象?

0

明白了:

public static BufferedImage getImage(String imagefile) { 

    BufferedImage image = null; 
    BufferedImage image_copy = null; 

    try { 

     image = javax.imageio.ImageIO.read(new java.io.File(imagefile));  
     image_copy = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); 

     int trans = image.getRGB(0,0); 
     final int width = image.getWidth(); 
     int[] imgData = new int[width]; 

     for (int y = 0; y < image.getHeight(); y++) { 
      // fetch a line of data from each image 
      image.getRGB(0, y, width, 1, imgData, 0, 1); 

      for (int x = 0; x < width; x++) 
       if (imgData[x] == trans) 
        imgData[x] &= 0x00FFFFFF; 

      // replace the data 
      image_copy.setRGB(0, y, width, 1, imgData, 0, 1); 
     }   

    } catch (Exception e) { 

      e.printStackTrace(); 

    } 

    return image_copy; 

} 

感謝您的幫助!

看起來像是一個邏輯錯誤。

+0

那麼,接受爲您提供幫助的答案,以便讓人們知道問題已得到解答。 – camickr 2009-12-11 07:19:08