在我的应用程序中,我的应用程序文件夹中有许多图像,当我尝试使用静态的代码时,我需要合并到一个映像中。我需要如何动态地将代码组合到单个图像中并将其存储在应用程序文件夹中。
我的代码:
.cs
protected void Button1_Click(object sender, EventArgs e)
{
string img1path = MapPath("~/AppImages/12162016/ScnMeet1.PNG");
// Load two Images to be combined into Image Objects
System.Drawing.Image img1 = System.Drawing.Image.FromFile(img1path);
var images = new[] { img1, img2, img3, img4, img5, img6, img7 };
using (Bitmap FinalBitmap = new Bitmap(images.Max(img => img.Width), images.Sum(img => img.Height)))
{
using (Graphics FinalImage = Graphics.FromImage(FinalBitmap))
{
// Draw the first image staring at point (0,0) with actual width and height of the image, in final image
FinalImage.DrawImage(img1, new Rectangle(0, 0, img1.Width, img1.Height));
// and Draw the second image staring at point where first image ends in the final image and save changes
FinalImage.DrawImage(img2, 0, img1.Height);
FinalImage.DrawImage(img3, 0, img1.Height + img2.Height);
FinalImage.DrawImage(img4, 0, img1.Height + img2.Height + img3.Height);
FinalImage.DrawImage(img5, 0, img1.Height + img2.Height + img3.Height + img4.Height);
FinalImage.DrawImage(img6, 0, img1.Height + img2.Height + img3.Height + img4.Height + img5.Height);
FinalImage.DrawImage(img7, 0, img1.Height + img2.Height + img3.Height + img4.Height + img5.Height + img6.Height);
FinalImage.Save();
// Write the bitmap to an image file and you’re done
FinalBitmap.Save(MapPath("~/ResultImages/Resultimg.PNG"));
MergedCombinedImage.ImageUrl = "~/ResultImages/Resultimg.PNG";
}
}
}
使用上述代码,我有7张图像,我采用7个图像路径。如果我有15张图像,我将拍摄15个图像路径,我认为这是不正确的,但是我该如何动态地进行任何一个,请给我一些想法以动态化。
图像描述在这里谢谢
一个想法将在静态方法中使用 params 关键字与 foreach loop 结合使用。
免责声明,这是不是工作代码(只是一个方向的指南):
static void MergeImages(params Image[] images) //allows a variable number of arguments
{
int currentImgHeight = 0;
using (Bitmap FinalBitmap = new Bitmap(images.Max(img => img.Width), images.Sum(img => img.Height)))
{
using (Graphics FinalImage = Graphics.FromImage(FinalBitmap))
{
foreach (var img in images)
{
currentImgHeight += img.Height; //counter upwards for height
FinalImage.DrawImage(img, img.Width, currentImgHeight);
}
FinalImage.Save();
FinalBitmap.Save(MapPath("~/ResultImages/Resultimg.PNG"));
MergedCombinedImage.ImageUrl = "~/ResultImages/Resultimg.PNG";
}
}
}
可能的示例调用:
var files = Directory.GetFiles(Server.MapPath("~/AppImages/12162016/"));
List<Image> images = new List<Image>();
foreach (var file in files)
{
images.Add(Image.FromFile(file));
}
MergeImages(images.ToArray());