将PNG图像保存到内存流会导致错误

Syl*_*ain 9 c# iis wpf asp.net-web-api windows-server-2012-r2

我有一个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;
  }
Run Code Online (Sandbox Code Playgroud)

我有三个Web服务器,其中一个上面的代码导致此错误:A generic error occurred in GDI+.at at System.Drawing.Image.Save().

有关服务器的更多细节

服务器运行不同的OS版本:

  • 服务器1,工作正常:Windows Server 2012 Standard
  • 服务器2,工作正常:Windows Server 2008 R2 Standard
  • 服务器3,无法正常工作:Windows Server 2012 R2数据中心(核心)

JPEG是一种解决方法

我已经更改了上面的代码以返回JPEG而不是PNG,并修复了问题.

  img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Run Code Online (Sandbox Code Playgroud)

我必须发送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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 0

1) .NET框架>=3.0应该有一个内置的编码器。检查是否有适合正确图像 MIME 类型的编码器。

 public static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
             string lookupKey = mimeType.ToLower(); 
            ImageCodecInfo foundCodec = null; 
            if (Encoders.ContainsKey(lookupKey))
            { 
                foundCodec = Encoders[lookupKey];
            } 
            return foundCodec;
        }
Run Code Online (Sandbox Code Playgroud)

(您将需要查找编码器)

  private static Dictionary<string, ImageCodecInfo> _encoders;

        /// <summary>
        ///     A quick lookup for getting image encoders
        /// </summary>
        private static Dictionary<string, ImageCodecInfo> Encoders
        {
            get
            {
                if (_encoders == null)
                {
                    _encoders = new Dictionary<string, ImageCodecInfo>();
                }
                if (_encoders.Count == 0)
                {
                    foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders())
                    {
                        _encoders.Add(codec.MimeType.ToLower(), codec);
                    }
                }
                return _encoders;
            }
        }
Run Code Online (Sandbox Code Playgroud)

然后您可以尝试使用您最喜欢的编码器保存或获取字节

  public static void Save(string path, Image img, string mimeType)
        {
            using (var ms = File.OpenWrite(path))
            {
                ImageCodecInfo encoder = GetEncoderInfo(mimeType);
                img.Save(ms, encoder, null); 
            }
        }
Run Code Online (Sandbox Code Playgroud)

2)有时我在保存索引图像时遇到问题。查看yourImage.PixelFormat并根据需要尝试将图像转换为其他图像。