2011-07-27 143 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 ))