2011-12-07 63 views
1

我試圖(在Java中)在合併2種顏色時得到最終的顏色,頂部有alpha透明度的顏色。基本上,我正在嘗試爲圖像分配背景顏色,但我已將其分解爲每個像素單獨更改。我看過幾篇文章,包括this one,都無濟於事。有人知道如何進行這種RGBA/RGB混色?我目前的代碼使用PNG文件:將2個RGB顏色與Alpha結合使用

PNG Image

,併產生這種JPG:

JPG Image

這是我目前使用的功能。爲演示圖片背景設置爲全藍,或255

public static void PNGToJPEGConvert(String PNGPath, String NewJPEGPath, int BackColor) throws IOException { 
    try { 
     BufferedImage bufferedImage = ImageIO.read(new File(PNGPath)); 
     BufferedImage newImage; 
     int R1, G1, B1, R2 = (BackColor & 0xFF0000) >> 16, G2 = (BackColor & 0xFF00) >> 8, B2 = (BackColor & 0xFF), W1, W2, W3, M1, M2, R3, G3, B3; 
     float br; 
     newImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); 
     for(int x=0; x < bufferedImage.getWidth(); x++) { 
      for(int y=0; y < bufferedImage.getHeight(); y++) { 
       R1 = BufferedImageGetPixelARGB(bufferedImage, "R", x, y); 
       G1 = BufferedImageGetPixelARGB(bufferedImage, "G", x, y); 
       B1 = BufferedImageGetPixelARGB(bufferedImage, "B", x, y); 
       W1 = Math.min(R1, Math.min(G1, B1)); 
       W2 = Math.min(R2, Math.min(G2, B2)); 
       R1 -= W1; 
       G1 -= W1; 
       B1 -= W1; 
       R2 -= W2; 
       G2 -= W2; 
       M1 = Math.max(R1, Math.max(G1, B1)); 
       M2 = Math.max(R2, Math.max(G2, B2)); 
       br = (M1 + M2)/(2*BufferedImageGetPixelARGB(bufferedImage, "A", x, y)); 
       R3 = (int) ((R1 + R2) * br); 
       G3 = (int) ((G1 + G2) * br); 
       B3 = (int) ((B1 + B2) * br); 
       W3 = (W1 + W2)/2; 
       R3 += W3; 
       G3 += W3; 
       B3 += W3; 
       newImage.setRGB(x, y, RGBValuesToInt(R3, G3, B3)); 
      } 
     } 
     try { 
      ImageIO.write(newImage, "jpg", new File(NewJPEGPath)); 
     } catch(Exception e) { 

     } 
    } catch(Exception e) { 

    } 
} 

感謝您的幫助一個int, -Neil

回答

2

基本上它是

float masking_factor = mask_value/255.0; 
composed_value = int(
    source_pixel_value * (1 - masking_factor) + 
    overlay_pixel_value * masking_factor 
); 

我們假設所有值均爲8位,即0至255,而mask爲單色。其中mask是完全黑色的,它是完全透明的,只有源像素可見。其中mask是完全白色的,它是完全不透明的,只有重疊像素可見。介於兩者之間的值會產生中等不透明度。

但是,如果阿爾法混合是只有事情你想實現,有更好的方法來做到這一點比單個像素的工作。見Graphics2D及其.setComposite()方法。

3
public static Color mixColorsWithAlpha(Color color1, Color color2, int alpha) 
{ 
    float factor = alpha/255f; 
    int red = (int) (color1.getRed() * (1 - factor) + color2.getRed() * factor); 
    int green = (int) (color1.getGreen() * (1 - factor) + color2.getGreen() * factor); 
    int blue = (int) (color1.getBlue() * (1 - factor) + color2.getBlue() * factor); 
    return new Color(red, green, blue); 
} 

這將與在color1上繪製color2(使用給定的alpha值)相同。

+0

這幫助我混合一種顏色與黑色來獲得自己的黑暗版本。謝謝! – speedynomads