我有一个WebAPI端点(托管在IIS中),从数据库(字节数组)读取图像并以PNG格式返回它们。这段代码很简单:
Image img = ImageHelper.ReadFromDatabase(…);
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new ByteArrayContent(ms.ToArray());
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
response.ConfigureResponseCachability(parseConceptVersion, TimeSpan.FromHours(1));
return response;
}
我有三个网站服务器,其中一个会出现上述代码引起的错误:A generic error occurred in GDI+.
at at System.Drawing.Image.Save()
。
更多关于服务器的细节
这些服务器运行不同的操作系统版本:
- 服务器1,工作正常:Windows Server 2012 Standard
- 服务器2,工作正常:Windows Server 2008 R2 Standard
- 服务器3,无法工作:Windows Server 2012 R2 Datacenter (Core)
JPEG是一种解决方法
我已将上述代码更改为返回JPEG而不是PNG,并解决了问题。
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
我必须发送PNG图像,因此我需要找到根本原因。
使用WPF类而非Windows Form类
我将代码转换为使用WPF类(System.Windows.Media),而不是Windows Form类。结果很有趣:我也无法创建PNG,这次错误是The component registration is invalid. (Exception from HRESULT: 0x88982F8A)
在System.Windows.Media.Imaging.BitmapEncoder.SaveFrame()
处。
服务器上是否缺少某些东西?
我的服务器是否缺少保存PNG所必需的低级组件?
谢谢
@Chris Pratt要求查看从字节数组创建图像的代码。在WebAPI代码和SqlDataReader调用之间有几个层次,但这里是从数据库中读取的字节数组转换为图像的代码。
/// <summary>
/// Creates a bitmap from a byte array
/// </summary>
public static Bitmap CreateBitmapFromBytes(byte[] bytes, int width, int height)
{
// Make sure bytes were specified.
if (bytes == null ||
bytes.Length == 0)
{
return null;
}
using (MemoryStream imageStream = new MemoryStream(bytes))
{
Bitmap bitmap;
try
{
bitmap = (Bitmap)Bitmap.FromStream(imageStream);
}
catch(ArgumentException)
{
return GetEmptyBitmap(width, height);
}
using (bitmap)
{
return new Bitmap(bitmap, width, height);
}
}
}