将两个图像合并为一个新图像

时间:2011-08-26 14:49:44

标签: c# .net image bitmap

我有两个不同尺寸的JPEG文件:

Image1(Width1,Height1)

Image2(Width2,Height2)

我想创建Image3(Width3,Height3),左侧是Image1,右侧是Image2。

3 个答案:

答案 0 :(得分:41)

这样的东西会为你提供一张新图像,并带有两张原始图像。

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

答案 1 :(得分:13)

我有类似的问题。 使用此功能,您可以将多个位图合并为单个图像

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

        var width = 0;
        var height = 0;

        foreach (var image in enumerable)
        {
            width += image.Width;
            height = image.Height > height
                ? image.Height
                : height;
        }

        var bitmap = new Bitmap(width, height);
        using (var g = Graphics.FromImage(bitmap))
        {
            var localWidth = 0;
            foreach (var image in enumerable)
            {
                g.DrawImage(image, localWidth, 0);
                localWidth += image.Width;
            }
        }
        return bitmap;
    }

答案 2 :(得分:0)

  

您可以尝试

     

您需要使用的库

using System.Drawing; using System.Drawing.Imaging; //controller

public ActionResult Image()     
    {
        var bitmap = GetBitmap(); // The method that returns List<Bitmap>
        var width = 0;
        var height = 0;
        foreach (var image in bitmap)
        {
            width += image.Width;
            height = image.Height > height
                ? image.Height
                : height;
        }
        var bitmap2 = new Bitmap(width, height);
        var g = Graphics.FromImage(bitmap2);
        var localWidth = 0;
        foreach (var image in bitmap)
        {
            g.DrawImage(image, localWidth, 0);
            localWidth += image.Width;
        }

        var ms = new MemoryStream();

        bitmap2.Save(ms, ImageFormat.Png);
         var   result = ms.ToArray();
         //string base64String = Convert.ToBase64String(result); 
         return File(result, "image/jpeg"); //Return as file result
        //return base64String;
    }
//this method returns List<Bitmap>
public List<Bitmap> GetBitmap()
    {
        var lstbitmap = new List<Bitmap>();
        var bitmap = new Bitmap(@"E:\My project\ProjectImage\ProjectImage\BmImage\1525244892128.JPEG");
        var bitmap2 = new Bitmap(@"E:\My project\ProjectImage\ProjectImage\BmImage\1525244892204.JPEG");
        var bitmap3 = new Bitmap(@"E:\My project\ProjectImage\ProjectImage\BmImage\3.jpg");
        lstbitmap.Add(bitmap);
        lstbitmap.Add(bitmap2);
        lstbitmap.Add(bitmap3);
        return lstbitmap;
    }
  

祝你好运!