我有一个ASPX页面,它将查询字符串中的任何内容呈现为垂直文本并返回PNG。它运作得很好。
我只有一个客户遇到了问题。每隔几天,该页面就会停止工作并抛出可怕的GDI+“通用”错误。
我不知道为什么会出现错误,也不知道它最终为什么消失了。 我向他们的安装中添加了一个测试ASPX文件,运行了类似的代码,进行了一些变化,以确定问题所在。 我发现如果将ImageFormat从Png更改为Jpeg,则错误会消失。
我可以考虑更改产品,以渲染JPEG而不是PNG。 但是,我无法知道这是否会像现在一样开始间歇性出错。
有人知道可能引起此类问题的原因吗? 谢谢! 以下是代码。
更新:客户服务器是运行IIS 7.5的Windows Server 2008 R2框,我的应用程序运行在.NET 4.0上。
我只有一个客户遇到了问题。每隔几天,该页面就会停止工作并抛出可怕的GDI+“通用”错误。
Error: System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+.
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(Stream stream, ImageFormat format)
...
我不知道为什么会出现错误,也不知道它最终为什么消失了。 我向他们的安装中添加了一个测试ASPX文件,运行了类似的代码,进行了一些变化,以确定问题所在。 我发现如果将ImageFormat从Png更改为Jpeg,则错误会消失。
我可以考虑更改产品,以渲染JPEG而不是PNG。 但是,我无法知道这是否会像现在一样开始间歇性出错。
有人知道可能引起此类问题的原因吗? 谢谢! 以下是代码。
更新:客户服务器是运行IIS 7.5的Windows Server 2008 R2框,我的应用程序运行在.NET 4.0上。
protected void Page_Load(object sender, EventArgs e)
{
byte[] image = GetImageBytes(this.Text);
if (image != null)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "image/png";
Response.OutputStream.Write(image, 0, image.Length);
}
}
private byte[] GetImageBytes(string text)
{
var font = new Font("Tahoma", 11, FontStyle.Bold, GraphicsUnit.Pixel);
// Create an image the size of the text we are writing
Bitmap img = new Bitmap(1,1);
var graphics = Graphics.FromImage(img);
int width = (int)graphics.MeasureString(text, font).Width;
int height = (int)graphics.MeasureString(text, font).Height;
img = new Bitmap(img, new Size(width, height));
// Draw the text onto the image
graphics = Graphics.FromImage(img);
graphics.Clear(Color.Transparent);
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.DrawString(text, font, new SolidBrush(Color.Black), 0, 0);
graphics.Flush();
// Rotate the image to be vertical
img.RotateFlip(RotateFlipType.Rotate270FlipNone);
var stream = new System.IO.MemoryStream();
img.Save(stream, ImageFormat.Png);
stream.Position = 0;
return stream.ToArray();
}