Home > Mobile >  How can I merge more than two images side by side?
How can I merge more than two images side by side?

Time:12-21

This merges two images, but what if I want to merge more than two ?

I'm not sure how to add another image or more.

private Bitmap MergeImages(Image image1, Image image2)
{
    Bitmap bitmap = new Bitmap(image1.Width   image2.Width, Math.Max(image1.Height, image2.Height));
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.DrawImage(image1, 0, 0);
        g.DrawImage(image2, image1.Width, 0);
    }
    
    bitmap.MakeTransparent();
    
    return bitmap;
}

For example 3 images :

private Bitmap MergeImages(Image image1, Image image2, Image image3)
{
    Bitmap bitmap = new Bitmap(image1.Width   image2.Width, Math.Max(image1.Height, image2.Height));
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.DrawImage(image1, 0, 0);
        g.DrawImage(image2, image1.Width, 0);
    }
    
    bitmap.MakeTransparent();
    
    return bitmap;
}

CodePudding user response:

Just write a loop, keeping track of the current width of all the drawn images:

private Bitmap MergeImages(IEnumerable<Image> images)
{
    var totalWidth = images.Sum(i => i.Width);
    var maxHeight = images.Max(i => i.Height);
    Bitmap bitmap = new Bitmap(totalWidth , maxHeight );
    var currentXPos = 0;
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        foreach(var image in images)
        {
            g.DrawImage(image, currentXPos, 0);
            currentXPos  = image.Width;
        }
    }

    bitmap.MakeTransparent();

    return bitmap;
}
  • Related