这种合并方式为画布合并,如果图片太多,会导致内存不足的错误
/// <summary>
/// 多张图片的合并(上下合并),可拓展为左右合并
/// </summary>
private byte[] CombinImage(List<Bitmap> list_bitmap)
{
var width = list_bitmap[0].Width;
//var width = Math.Max(img1.Width, img2.Width);
int height = 0;
foreach (var item in list_bitmap)
{
height += item.Height;
}
// 初始化画布(最终的拼图画布)并设置宽高
Bitmap bitMap = new Bitmap(width, height);
// 初始化画板
System.Drawing.Graphics g1 = System.Drawing.Graphics.FromImage(bitMap);
// 将画布涂为白色(底部颜色可自行设置)
g1.FillRectangle(Brushes.White, new System.Drawing.Rectangle(0, 0, width, height));
int pointy = 0;
for (int i = 0; i < list_bitmap.Count; i++)
{
if (i == 0)
{
pointy = 0;
g1.DrawImage(new Bitmap(list_bitmap[i]), 0, pointy, list_bitmap[i].Width, list_bitmap[i].Height);
}
else
{
pointy += list_bitmap[i - 1].Height;
g1.DrawImage(new Bitmap(list_bitmap[i]), 0, pointy + 10, list_bitmap[i].Width, list_bitmap[i].Height);
}
}
Image img = bitMap;
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.GetBuffer();
}
这种为流模式合并,可以解决内存问题
/// <summary>
/// 调用此函数后使此两种图片合并,类似相册,有个
/// 背景图,中间贴自己的目标图片
/// </summary>
/// <param name="sourceImg">底层图片</param>
/// <param name="destImg">上层图片</param>
public static System.IO.MemoryStream CombinImage(System.IO.MemoryStream sourceImgStream, System.IO.MemoryStream destImgStream/*, int iSrcWidth, int iSrcHight, int iDstWidth, int iDstHight*/)
{
System.Drawing.Image imgBack = System.Drawing.Image.FromStream(sourceImgStream); //底层图像
System.Drawing.Image img = System.Drawing.Image.FromStream(destImgStream); //上层图像
//从指定的System.Drawing.Image创建新的System.Drawing.Graphics
Graphics g = Graphics.FromImage(imgBack);
g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); // g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
//g.FillRectangle(System.Drawing.Brushes.Black, 16, 16, (int)112 + 2, ((int)73 + 2));//相片四周刷一层黑色边框
//g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
g.DrawImage(img, imgBack.Width - img.Width -100, 100, img.Width, img.Height);
GC.Collect();
//输出文件流
System.IO.MemoryStream ms = new System.IO.MemoryStream();
imgBack.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imgBack.Dispose();
return ms;
}