C# Stitch multiple pictures into one picture via System.Drawing.Common;

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Color = System.Drawing.Color;

 public static class ImageStitcher
 {
     public static Bitmap SticthImagesVertical(List<Bitmap> imgsList)
     {
         if (imgsList==null && !imgsList.Any())
         {
             return null;
         }

         int width = 0;
         int height = 0;
         foreach (var img in imgsList)
         {
             if (img.Width>width)
             {
                 width=img.Width;
             }
             height+=img.Height;
         }

         Bitmap finalImage = new Bitmap(width, height);
         using (Graphics g = Graphics.FromImage(finalImage))
         {
             g.Clear(Color.White);
             int offsetY = 0;
             foreach (var img in imgsList)
             {
                 g.DrawImage(img, new System.Drawing.Rectangle(0, offsetY, img.Width, img.Height));
                 offsetY+=img.Height;
             }
         }
         return finalImage;
     }
 }

 

 

await Task.Run(() =>
{
    var imgs = Directory.GetFiles(dir)
    .Select(x => new FileInfo(x))
    .OrderBy(x => x.CreationTime)
    .Select(x => x.FullName);

    var imgsGroups = imgs.Chunk(20);

    batchIdx=0;
    foreach (var imgGroup in imgsGroups)
    {
        List<Bitmap> bitmapsList = new List<Bitmap>();
        foreach (var bitmap in imgGroup)
        {
            bitmapsList.Add(new Bitmap(bitmap));
        }

        using (var bmp = ImageStitcher.SticthImagesVertical(bitmapsList))
        {
            string groupedImgFile = System.IO.Path.Combine(groupDir, $"Group_{++batchIdx}.jpg");
            bmp.Save(groupedImgFile, System.Drawing.Imaging.ImageFormat.Jpeg);
        }

        foreach (var bmp in bitmapsList)
        {
            bmp.Dispose();
        }
    }
});

 

 

 

image

 

 

 

 

 

 

image

 

posted @ 2025-08-30 21:02  FredGrit  阅读(9)  评论(0)    收藏  举报