合并图、切割图
拼接图
/// <summary> /// 拼接图 /// 1,纵向拼接 /// 2,白底填充 /// 3,以最左边为准(x=0),进行拼接 /// </summary> /// <param name="imageList"></param> /// <returns></returns> public static Image MergeImage(List<Image> imageList, int maxWidth = 2000) { if (imageList.Count == 0) return null; try { int height = imageList.Sum(x => x.Height); int width = Math.Min(imageList.Max(x => x.Width), maxWidth); // 构建空白大图 Bitmap bitmap = new Bitmap(width, height); // 创建画布 var g = Graphics.FromImage(bitmap); // 设置为白底 g.Clear(Color.White); // 合并图 int current_height = 0; foreach (var img in imageList) { g.DrawImage(img, 0, current_height); current_height += img.Height; } // 释放资源 g.Dispose(); return bitmap; } catch (Exception ex) { return null; } }
切割图
/// <summary> /// 切割图 /// 1,指定位置指大小切割图 /// </summary> /// <param name="img"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> public static Image CutImage(Image img, int x, int y, int width, int height) { try { Bitmap bitmap = new Bitmap(width, height); var g = Graphics.FromImage(bitmap); g.Clear(Color.White); g.DrawImage(img, new Rectangle(0, 0, width, height), new Rectangle(x, y, width, height), GraphicsUnit.Pixel); g.Dispose(); return bitmap; } catch (Exception ex) { return null; } } /// <summary> /// 切割图:将一张大图,纵向切割成若干个小图 /// </summary> /// <param name="bigImage"></param> /// <param name="maxWidth"></param> /// <param name="maxHeight"></param> /// <returns></returns> public static List<Image> SplitImage(Image bigImage, int maxWidth = 2000, int maxHeight = 1500) { try { int bigHeight = bigImage.Height; List<Image> list = new List<Image>(); int x = 0; int y = 0; int width = Math.Min(bigImage.Width, maxWidth); int height = maxHeight; while (y < bigHeight) { var img = CutImage(bigImage, x, y, width, height); if (img != null) list.Add(img); y += height; } return list; } catch (Exception ex) { return null; } }