2011-07-27 138 views
5

可能重複:
Merging two images in C#/.NET合併兩個PNG圖像的透明度和保持透明度

我有兩個PNG格式的圖片和透明度定義都有。我需要將它們合併成一個新的PNG圖像,但不會丟失結果中的任何透明度。將第一個圖像視爲主圖像,第二個圖像用於添加疊加層,例如添加/編輯/刪除指示符。我正在嘗試創建一個小實用程序,它將採用主圖像和一組覆蓋圖,然後生成將它們組合在一起的合成輸出圖像集。

似乎有會有很多與PHP的解決方案,但沒有對C#/

+2

可能的重複:http://stackoverflow.com/q/465172/15667。 看看這是否有幫助。 – xan

+0

WinForms,ASP.Net或WPF? –

回答

17

這應該工作。

Bitmap source1; // your source images - assuming they're the same size 
Bitmap source2; 
var target = new Bitmap(source1.Width, source1.Height, PixelFormat.Format32bppArgb); 
var graphics = Graphics.FromImage(target); 
graphics.CompositingMode = CompositingMode.SourceOver; // this is the default, but just to be clear 

graphics.DrawImage(source1, 0, 0); 
graphics.DrawImage(source2, 0, 0); 

target.Save("filename.png", ImageFormat.Png); 
+0

感謝這對我工作! –

1

可惜你沒有提到你怎麼弄的像素的答案,

所以p代碼:

// The result will have its alpha chanell from "first", 
// the color channells from "second". 

assert (first.width = second.width) 
assert (first.height = second.height) 

for y in 0..height 
    for x in 0..width 
     RGBA col_first = first(x,y) 
     RGBA col_second = second(x,y) 

     result(x,y) = RGBA(col_second.r, 
          col_second.g, 
          col_second.b, 
          col_first.a ))