views:

802

answers:

2

I am trying to draw two images side-by-side using the C# Drawing namespace. Here is a very simple example that assumes we have two images of the same height:

Image[] oldImages = GetOldImages();

var newImage = new Bitmap(oldImages[0].Width + oldImages[1].Width, 800);

using (var newImageGraphics = Graphics.FromImage(newImage))
{
    newImageGraphics.DrawImage(oldImages[0], 0, 0);
    newImageGraphics.DrawImage(oldImages[1], oldImage[0].Width, 0);
    newImageGraphics.Save();
}

This works OK if the resolution of the two old images are the same.

However, if the resolutions are different then the image is resized, causing problems. For example, if the first image has a different resolution, then the second image will be positioned incorrectly.

Does anyone know how I can fix this problem easily? Ideally I want the original image's height and width to remain the same when they are drawn on to the new image.

+1  A: 

Basically you'll need to resize the second image before adding to the new image.

Though as you say you want to retain the original height and width you'll need to change the canvas size of the second image. This increases the size of the image by adding empty space around the actual image. If the second image is larger than the first you'll need to do this to the first image instead.

ChrisF
+1  A: 

Try this trick:

Bitmap picture_1 = new Bitmap(picture_1_path);
Graphics graphics = Graphics.FromImage(picture_1);
Bitmap picture_2 = new Bitmap(picture_2_path);
picture_2.SetResolution(graphics.DpiX, graphics.DpiY);

//Then do with pictures anything