Merge two PNG images with transparency and maintain transparency

Possible duplicate:
Combining two images in C # /. NET

I have two PNG images, and both have transparency. I need to combine them together in a new png image, but without losing the transparency of the result. Think of the first image as the main image, and the second to add an overlay, for example, to add / edit / delete. I am trying to create a small utility that takes the main image and a set of overlays, and then creates a resulting set of output images that combine them.

There seems to be a lot of answers with solutions for PHP, but nothing for C # /

+5
source share
2 answers

That 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);
+17
source

Unfortunately, you didn’t specify how you get pixels,

therefore 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  ))
+1
source

All Articles