我创建了一种方法,该方法可以将图像列表结合在一起也形成单个图像。
代码现在只能处理4张图像,我想对其进行更改,以便可以处理4张以上的图像。
我正在尝试创建一种简单的方法。
这是代码,请告诉我是否有一种简单的好方法。
public static byte[] CombineImages(params string[] imageUrl)
{
var staticWidth = 200;
var staticHeight = 200;
// download the images from the url and then resize them
List<Bitmap> images = imageUrl
.Select((x, i) => i <= 3 ? GenerateThumbImage(GetImage(x), staticWidth, staticHeight) : null)
.Where(x => x != null).ToList();
var nIndex = 0;
var max_Height = 0;
var max_Width = 0;
var counter = 0;
foreach (var image in images)
{
max_Height = Math.Max(max_Height, image.Height);
if (counter <= 1)
max_Width += image.Width;
counter++;
}
// the container of the joined images
var imgContainer = new Bitmap(max_Width, imageUrl.Count() > 2 ? max_Height * 2 : max_Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
var g = Graphics.FromImage(imgContainer);
g.Clear(Color.Transparent);
// and here is where i need your help to simplify it
// and make it more dynamic so it could handle more then 4 images
for (var i = 0; i < images.Count(); i++)
{
var img = images[i];
if (i == 0 || nIndex == 0)
{
g.DrawImage(img, new Point(0, i == 0 ? 0 : max_Height));
max_Width = img.Width;
}
else
{
g.DrawImage(img, new Point(max_Width, i > 2 ? max_Height : 0));
max_Width += img.Width;
}
if (nIndex >= 1)
nIndex = 0;
else nIndex++;
img.Dispose();
}
g.Dispose();
using (var memoryStream = new MemoryStream())
{
imgContainer.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
return memoryStream.ToArray();
//var base64String = Convert.ToBase64String(memoryStream.ToArray());
//img3.Dispose();
//return base64String;
}
}