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

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

DDD
DDDOriginal
2025-01-04 12:50:44373browse

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");

Step 2: Create a New Bitmap (Canvas)

int width = 500;
int height = 500;

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

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);

Step 4: Calculate Overlay Position

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

Step 5: Draw the Overlay Image

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

Step 6: Save the Merged Image

bitmap.Save("merged.png");

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:
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