MrBeanzy
MrBeanzy

Reputation: 2296

Replace part of an image with another in C# with WinForms

I have a big .PNG that has many little images on it. I want to replace part of the big image with a smaller one. So at X and Y coordinates, that part of the image will be replaced starting from the top left hand corner, while still leaving the rest of the original image intact.

I have been reading about the Graphics methods on MSDN and also had a look for some examples of a similar thing but didn't find much.

Had anyone done anything similar?

Thanks!

Upvotes: 2

Views: 2491

Answers (1)

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

I would suggest this approach. X and Y are the coordinates on the big image where you want to put the small one. You can check the DrawImage method overloads, there are 30 of them but I think this one best suites your case:

Bitmap bigBmp = new Bitmap("bigBmp.png");
Bitmap smallBmp = new Bitmap("smallBmp.png");
Graphics g = Graphics.FromImage(bigBmp);

Rectangle destRect = new Rectangle(x, y, smallBmp.Width, smallBmp.Height);
Rectangle sourceRect = new Rectangle(0, 0, smallBmp.Width, smallBmp.Height);

g.DrawImage(smallBmp, destRect, sourceRect, GraphicsUnit.Pixel);
g.Dispose();

EDIT: Based on the comment of KvanTTT, I have decided to add another solution to the question using DrawImageUnscaled because it is the fastest way to draw images. There are four overloads of this method, but this one is the simplest one that matches the question.

Bitmap bigBmp = new Bitmap("bigBmp.png");
Bitmap smallBmp = new Bitmap("smallBmp.png");

Graphics g = Graphics.FromImage(bigBmp);
g.DrawImageUnscaled(smallBmp, x, y);
g.Dispose();

Upvotes: 9

Related Questions