Mike
Mike

Reputation: 2601

Combining two image into one new image

I'm trying the replicate the imagecopy PHP function in .NET. I have two images which I need to combine into one new image. One image is a template and I need to fit the second image into the template and then save the result as a new file. Here's what I have so far:

//Sized Image
Bitmap sizedImg = (Bitmap)Image.FromFile(Server.MapPath("~/ImageUploads/") + sizedImageName);
sizedImg.MakeTransparent(Color.White);

//Template Image
Bitmap template = (Bitmap)Image.FromFile(Server.MapPath("~/Assets/img/frame_sm.jpg"));

//Combine the two
Graphics newImage = Graphics.FromImage(template);
newImage.DrawImage(sizedImg, 96, 12, 232, 230);
newImage.Save();

//Save the new image
string fileName =  String.Format("{0}_sizedFB.jpg", originalImageName.Substring(0, originalImageName.IndexOf("_")));
//? Save

First, is this the correct code to combine the two images into one? And if so, how do I save the new image to disk?

Thank you.

Upvotes: 2

Views: 3394

Answers (1)

Alexander Galkin
Alexander Galkin

Reputation: 12534

First you have to create a new bitmap from your opened template file in order not to modify your template but rather to create a new image basing upon your template.

Bitmap template = (Bitmap)Image.FromFile(Server.MapPath("~/Assets/img/frame_sm.jpg"));
Bitmap newimage = new Bitmap(template);

Then you draw your image on this new image:

Graphics newImage = Graphics.FromImage(newimage);
newImage.DrawImage(sizedImg, 96, 12, 232, 230);

And finally you save your new image to a given file:

string fileName =  String.Format("{0}_sizedFB.jpg", originalImageName.Substring(0, originalImageName.IndexOf("_")));
newImage.Save(fileName, ImageFormat.Png);

Upvotes: 1

Related Questions