2014-11-23 53 views
0

我有一個JavaBufferedImage。前景是黑色,背景是透明的。我想將圖像重新着色爲紅色。如何更改Java緩衝圖像的顏色

我已閱讀其他人的帖子,並嘗試使用此代碼,但是當我運行它時,我的圖像完全透明。

有沒有人有任何想法?我是Java 2D圖像處理庫的新手。謝謝。

imageIcon= new ImageIcon(getImageURL("/ImagesGun/GunBase.png")); 
    gunBaseImage= Utilities.toBufferedImage(imageIcon.getImage()); 

    int red = 0x00ff0000; 
    int green = 0x0000ff00; 
    int blue = 0x000000ff; 

    int width = gunBaseImage.getWidth(); 
    int height = gunBaseImage.getHeight(); 

    //Loop through the image and set the color to red 
    for(int x = 0; x < width; x++){ 
     for(int y = 0; y < height; y++){ 
      long pixel = gunBaseImage.getRGB(x, y); 
      if(pixel != 0){ 
       red = 0x00ff0000; 

       gunBaseImage.setRGB(x,y,red); 
      } 

     } 
    } 
+0

爲每個像素調用getRGB和setRGB會變得很慢,因爲這些方法試圖進行全色空間轉換。對於圖像處理,最好訪問BufferedImage後面的int數組。 – lbalazscs 2014-11-24 06:54:14

回答

3

您正在使用完全透明的紅色值。顏色定義中的第一個條目是alpha值。如果你想要一個完全不透明的顏色,你需要使用ff作爲第一個值。因此你的紅色應該是0xffff0000,你的綠色0xff00ff00等等。這也意味着黑色是ff000000。

+0

這是真的。我認爲,如果他想保持不透明性,他必須掩蓋這一點,並處理顏色本身的價值,這意味着他需要改變他的'if(pixel!= 0)'檢查,對吧?然後,在他的if()塊中,他需要進行按位AND操作,將原始不透明度添加到他想要的顏色。 – hfontanez 2014-11-23 16:12:34

+0

我的想法正是@hfontanez。這就是爲什麼我提到不透明的黑色是0xff000000,所以他可以做'if(pixel!= 0xff000000)'。 – 2014-11-23 16:14:32

+0

工作正常!謝謝@Matthew !!! – user1104028 2014-11-24 04:34:48