7

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#/

Community
  • 1
  • 1
Phil Wright
  • 22,580
  • 14
  • 83
  • 137
  • 2
    Possible duplicate of: http://stackoverflow.com/q/465172/15667. See if this helps. – xan Jul 27 '11 at 10:20

2 Answers2

26

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);
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
0

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  ))
Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130