G.drawimage draws with incorrect size

Im creating a big bitmap which contains some smaller images from files. The images have both a size of 250px, but one of them gets smaller and the other bigger than 250px. I'm just using the basic g.drawimage method, so I don't get what I do wrong.

string[] imagePaths = Directory.GetFiles(@"C:\Users\admin\Desktop\Images");
ArrayList images = new ArrayList();

foreach (var item in imagePaths)
    images.Add(new Bitmap(item, true));

Bitmap list = new Bitmap(840, 1188);

Graphics g = Graphics.FromImage(list);

int size = 0;

for (int i = 0; i < images.Count; i++)
{
    g.DrawImage((Bitmap)images[i], new Point(10, (i + 1) * 10 + size));
    Bitmap bmp = (Bitmap)images[i];
    Console.WriteLine(bmp.Height);
    Font drawFont = new Font("Arial", 16);
    size += bmp.Height;
    g.DrawString(imagePaths[i].Substring(imagePaths[i].LastIndexOf("\\") + 1, imagePaths[i].Length - imagePaths[i].LastIndexOf("\\") - 4), drawFont, Brushes.Black, new Point(bmp.Width + 30, (i + 1) * 10 + size / 4));
}    

list.Save(@"C:\Users\admin\Desktop\list.png", ImageFormat.Png);

Solution 1:

You don't set the dpi values. These are honored in DrawImage, so you need to set them with bitmap.SetResolution(dpix, dpiy). When they are different in the images the results will be too. You can get the 'correct' one from the Graphics object g or decide what you want.

Quick fix:

        for (int i = 0; i < images.Count; i++)
        {
            ((Bitmap)images[i]).SetResolution(g.DpiX, g.DpiY);
            g.DrawImage((Bitmap)images[i], new Point(10, (i + 1) * 10 + size));
            Bitmap bmp = (Bitmap)images[i];
            ...
        }

Note that the newly created bitmap uses the screen dpi resolution as its default. If you want to control the dpi you need to set them for list as well!

Also note the I didn't change your code; to simplify the last line should really move to the top of the loop and then bmp be used instead of the array element..