我正在开发一个asp.net C#webforms项目。我必须调试一个问题,偶尔我得到" GDI +"中发生了一般性错误。错误。这可能是由于太多人同时访问该网站。为了模仿它,我想创建一个for循环来创建数千个图像并通过占位符显示它。问题是,循环运行,只显示最后一个图像。我想看到在循环中创建的每个图像都显示在页面上。以下是代码:
protected void btnGenerateBarCode_Click(object sender, System.EventArgs e)
{
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
var codabar = new ZXing.BarcodeWriter();
codabar.Options = options;
codabar.Format = ZXing.BarcodeFormat.CODE_128;
for (int i = 1000; i < 2000; i++)
{
using (Bitmap bitMap = new Bitmap(codabar.Write(i.ToString())))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
}
//the placeholder control on the page
plBarCode.Controls.Add(imgBarCode);
}
}
}
答案 0 :(得分:0)
protected void btnGenerateBarCode_Click(object sender, System.EventArgs e)
{
var codabar = new ZXing.BarcodeWriter();
codabar.Options = options;
codabar.Format = ZXing.BarcodeFormat.CODE_128;
for (int i = 1000; i < 2000; i++)
{
using (Bitmap bitMap = new Bitmap(codabar.Write(i.ToString())))
{
// Here create the image control
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(byteImage);
}
//the placeholder control on the page
plBarCode.Controls.Add(imgBarCode);
}
}
}
这是因为您实际上只在循环外创建一个控件。将图像创建添加到循环内:
{{1}}