简体   繁体   中英

How can I merge more than two images side by side?

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM