DrawImage scales the original image.

I stitch several images vertically and horizontally to create one larger image (in which the total width and height are the sum of the width and height of the individual images) using Bitmapand System.Drawing.Graphicsin C #. The size of individual images is 256 px by 256 px.

When I use DrawImagefrom System.Drawing.Graphics, why do I get a scaled and / or enlarged version of the original image?


Here is the source image:

source image


When I get the image programmatically and write to a file in code, I get the following:

var result = httpClient.GetStreamAsync(/* url */);
var bitmap = new Bitmap(await result);
...
using (var memory = new MemoryStream())
{ 
   using (var fs = new FileStream(/* path */, FileMode.OpenOrCreate, FileAccess.ReadWrite))
   {
        bitmap.Save(memory, ImageFormat.Png); // I save to .png if that makes a difference
        var bytes = memory.ToArray();
        await fs.WriteAsync(bytes, 0, bytes.Length);
   }
}

software image search in code

I do not see the difference. So far, so good.


However, when I try to stitch images horizontally, I get the following:

Note. For reference, the image above is on the far right corner of the stitched image below.

horizontally stitched image

, , , .


, :

. byWidth - true, .

private Bitmap MergeImages(IEnumerable<Bitmap> images, bool byWidth)
{
    var enumerable = images as IList<Bitmap> ?? images.ToList();

    var width = 0;
    var height = 0;

    foreach (var image in enumerable)
    {
        if (byWidth)
        {
            width += image.Width;
            height = image.Height;
        }
        else
        {
            width = image.Width;
            height += image.Height;
        }
    }

    var bitmap = new Bitmap(width, height);
    using (var g = Graphics.FromImage(bitmap))
    {
        var localWidth = 0;
        var localHeight = 0;

        foreach (var image in enumerable)
        {
            if (byWidth)
            {
                g.DrawImage(image, localWidth, 0);
                localWidth += image.Width;
            }
            else
            {
                g.DrawImage(image, 0, localHeight);
                localHeight += image.Height;
            }
        }
    }

    return bitmap;
}
+4
1

, DrawImage DPI . , 72 DPI, 96 DPI , ( DPI, ). , (DPI) (DPI), .

, DrawImageUnscaled DPI. , DrawImageUnscaled DrawImage. .

: DrawImage. , :

g.DrawImage(img, 0, 0, img.Width, img.Height);

KB317174.

+4

Source: https://habr.com/ru/post/1663979/


All Articles