Home > Backend Development > C++ > How Can I Merge Two Images in C#/.NET?

How Can I Merge Two Images in C#/.NET?

DDD
Release: 2025-01-04 12:50:44
Original
442 people have browsed it

How Can I Merge Two Images in C#/.NET?

Merging Images in C#/.NET: A Practical Example

You have two images, a 500x500 transparent image and a 150x150 image, which you want to merge into a single 500x500 canvas. Here's a step-by-step solution in C# using the System.Drawing library:

Step 1: Load the Images

using System.Drawing;

Image background = Image.FromFile("background.png");
Image overlay = Image.FromFile("overlay.png");
Copy after login

Step 2: Create a New Bitmap (Canvas)

int width = 500;
int height = 500;

using var bitmap = new Bitmap(width, height);
Copy after login

Step 3: Draw the Background Image

using var canvas = Graphics.FromImage(bitmap);

canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.DrawImage(background,
                 new Rectangle(0,
                               0,
                               width,
                               height),
                 new Rectangle(0,
                               0,
                               background.Width,
                               background.Height),
                 GraphicsUnit.Pixel);
Copy after login

Step 4: Calculate Overlay Position

int x = (bitmap.Width / 2) - (overlay.Width / 2);
int y = (bitmap.Height / 2) - (overlay.Height / 2);
Copy after login

Step 5: Draw the Overlay Image

canvas.DrawImage(overlay,
                 new Rectangle(x,
                               y,
                               overlay.Width,
                               overlay.Height));
Copy after login

Step 6: Save the Merged Image

bitmap.Save("merged.png");
Copy after login

Additional Tips:

  • You can adjust the transparency of the overlay image using the Color.FromArgb() method.
  • If you want to resize the overlay image before merging, use the Image.Scale() method.
  • By manipulating the x and y variables, you can control the position of the overlay image on the canvas.

The above is the detailed content of How Can I Merge Two Images in C#/.NET?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template