If you have an image or images you want to apply another image on top of, it’s easy using CompositingMode & DrawImage in .net. Below is simple example showing a .jpg photo overlaying with a transparent .png file. You could use this technique to apply a custom watermark, logo, copyright, etc. to images. In the code are also some options for showing the image and saving the final file. Happy compositing!
Bitmap baseImage; Bitmap overlayImage; baseImage = (Bitmap)Image.FromFile(@"C:\temp\base.jpg"); overlayImage = (Bitmap)Image.FromFile(@"C:\temp\overlay.png"); var finalImage = new Bitmap(overlayImage.Width, overlayImage.Height, PixelFormat.Format32bppArgb); var graphics = Graphics.FromImage(finalImage); graphics.CompositingMode = CompositingMode.SourceOver; graphics.DrawImage(baseImage, 0, 0); graphics.DrawImage(overlayImage, 0, 0); //show in a winform picturebox pictureBox1.Image = finalImage; //save the final composite image to disk finalImage.Save(@"C:\temp\final.jpg", ImageFormat.Jpeg);
You’ll probably want to include:
using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging;
3 thoughts on “Overlaying / compositing images using c# – System.Drawing”
This works and I have three .png files in a picturebox. Is there a way to know as I mouse over the picturebox if I’m in png1 or 2 or 3
After Successful Overlaying.I want to again seperate the two composite image in two.How to Do ??
If you didn’t keep the base & overlay image objects, I don’t know of an easy way to separate these from the final, combined graphics object.