Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 468
Phil Wright Avatar asked Jul 27 '11 10:07

Phil Wright


People also ask

Does PNG preserve transparency?

Preserve background transparency in a GIF or PNG imageGIF and PNG‑8 formats support one level of transparency—pixels can be fully transparent or fully opaque, but not partially transparent.

Can PNG files be combined?

How to merge PNG files online. Select or drop your PNG documents to upload for merge. Once upload completes, drag PNG document thumbnails to rearrange them (if needed). Click on Merge Now button to start merge process.


2 Answers

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);
like image 78
Tim Rogers Avatar answered Oct 13 '22 01:10

Tim Rogers


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  ))
like image 22
Sebastian Mach Avatar answered Oct 12 '22 23:10

Sebastian Mach