2014-01-15 67 views
0

現在我可以將另一圖像的像素應用於pg到m的源圖像像素。但問題是我失去了漸變或淡化效果。更改java中透明像素的顏色

 public static void main(String[] args){ 
     try { 
      BufferedImage image = ImageIO.read(new File("c:\\m.png")); 
      BufferedImage patt = ImageIO.read(new File("c:\\pg.png")); 

      int f = 0; 
      int t = 0; 
      int n = 0; 
      BufferedImage bff = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); 
      for (int y = 0; y < image.getHeight(); ++y) { 
       for (int x = 0; x < image.getWidth(); ++x) { 
        int argb = image.getRGB(x, y); 
        int nrg = patt.getRGB(x, y); 

        if(((argb>>24) & 0xff) == 0) { 
           bff.setRGB(x, y, (255<<24)); 
        } else { 
           bff.setRGB(x, y, nrg); 
        }        
       } 
      } 
      System.out.println("Trans : " + t + " Normal : " + n); 
      File outputfile = new File("c://imagetest.png"); 
      ImageIO.write(bff, "png", outputfile); 
     } catch (IOException ex) { 

     } 

} 

謝謝。

+0

不要改變顏色...改變透明性 – sanket

+0

如何改變透明性 –

回答

2

0xff000000是不透明的黑色,0x00000000是完全透明的。

什麼是0(您選擇的顏色)?

是的,它是透明的。

嘗試0xff000000或甚至更好:argb^0xff000000,它只是改變透明度,而是。

   if(((argb>>24) & 0xff) == 0) { 
          bff.setRGB(x, y, argb^0xff000000); 
       } else { 
          bff.setRGB(x, y, argb); 
       }        
+0

是的,它現在工作,所有的透明像素都是白色的。 –

0

BufferedImage.setRGB(int x, int y, int rgb)rgb值由如下:

11111111 11111111 11111111 11111111 
Alpha Red  Green Blue

在你的代碼測試以下:

if (((argb >> 24) & 0xff) == 0) 

測試對於0的阿爾法值,從而完全透明。

當你發現它是真實的,你再與

bff.setRGB(x, y, 0); 

所以你再次設置爲透明設置RGB值設置爲0。

改變,要

bff.setRGB(x, y, (255<<24)); 

bff.setRGB(x, y, 0xff000000); //This should be better 

將其改爲不透明黑像素。這將有

一個二進制值

編輯:Moritz Petersen's solution應該更好地工作,因爲它保留了像素的顏色,同時消除透明度。

如果您想將其設置爲特定的顏色,你可以這樣做:

bff.setRGB(x, y, 0xffff0000); // red 
bff.setRGB(x, y, 0xff00ff00); // green 
bff.setRGB(x, y, 0xff0000ff); // blue 

或紅色,綠色和藍色值的任意組合。

+0

這真的很有幫助。 –

+0

如果我想將另一圖像的像素添加到此圖像不透明。 –

+0

'bff.setRGB(x,y,argb^0xff000000);'(來自Moritz Petersen)將實現這一點。你現在全白的原因是原始圖像將像素設置爲透明白色。 – ufis