Merge two png images with transparency and retain transparency [duplicate]
Possible Duplicate:
Merging two images in C#/.NET
I have two png format images and both have transparency defined. I need to merge these together into a new png image but without losing any of the transparency in the result. Think of the first image as the main image and the second is used to add an overlay, such as a add/edit/delete indicator. I am trying to create a little utility that will take a main image and a set of overlays and then generate the resultant set of output images that combine them.
There seem to be plenty of answers with solutions for PHP but nothing for C#/
This should work.
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);
Unfortunately you haven't mentioned how you get the pixels,
so p-code:
// 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 ))
精彩评论