服务器上的GetThumbnailImage中的C#内存不足exception

我正在运行以下代码,以便在用户向我们发送图像时创建缩略图:

public int AddThumbnail(byte[] originalImage, File parentFile) { File tnFile = null; try { System.Drawing.Image image; using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(originalImage)) { image = System.Drawing.Image.FromStream(memoryStream); } Log.Write("Original image width of [" + image.Width.ToString() + "] and height of [" + image.Height.ToString() + "]"); //dimensions need to be changeable double factor = (double)m_thumbnailWidth / (double)image.Width; int thHeight = (int)(image.Height * factor); byte[] tnData = null; Log.Write("Thumbnail width of [" + m_thumbnailWidth.ToString() + "] and height of [" + thHeight + "]"); using (System.Drawing.Image thumbnail = image.GetThumbnailImage(m_thumbnailWidth, thHeight, () => false, IntPtr.Zero)) { using (System.IO.MemoryStream tnStream = new System.IO.MemoryStream()) { thumbnail.Save(tnStream, System.Drawing.Imaging.ImageFormat.Jpeg); tnData = new byte[tnStream.Length]; tnStream.Position = 0; tnStream.Read(tnData, 0, (int)tnStream.Length); } } //there is other code here that is not relevant to the problem } catch (Exception ex) { Log.Error(ex); } return (tnFile == null ? -1 : tnFile.Id); } 

这在我的机器上工作正常,但是当我在测试服务器上运行时,我总是在行上得到一个内存不足的exception:using(System.Drawing.Image thumbnail = image.GetThumbnailImage(m_thumbnailWidth,thHeight,()=> false ,IntPtr.Zero))它不操纵大图像:它试图将480 * 640图像转换为96 * 128缩略图。 我不知道如何调查/解决这个问题。 有没有人有任何建议? 即使在我重新启动IIS之后,它总是会发生。 我最初认为图像可能已损坏但尺寸正确。 谢谢。

我们在ASP.Net服务器中使用GDI + Operations也遇到了类似的问题。 你提到你在服务器上运行的代码让我觉得,这可能是同样的问题。

请注意,服务器上不支持使用System.Drawing命名空间中的类。 致命的是,它可能会工作一段时间并突然(即使没有代码更改)错误发生。

我们不得不重写我们服务器代码的重要部分。

看评论:

注意事项

不支持在Windows或ASP.NET服务中使用System.Drawing命名空间中的类。 尝试在其中一种应用程序类型中使用这些类可能会产生意外问题,例如服务性能下降和运行时exception。 有关支持的替代方法,请参阅Windows Imaging Components。

来源: http : //msdn.microsoft.com/de-de/library/system.drawing(v=vs.110).aspx

非常感谢@vcsjones指出我正确的方向。 我没有使用image.GetThumbnailImage,而是调用:

 public static Image ResizeImage(Image imgToResize, Size size) { return (Image)(new Bitmap(imgToResize, size)); } 

麻烦的代码行现在是:

 using(Image thumbnail = ResizeImage(image, new Size(m_thumbnailWidth, thHeight))) 

我从Resize a Image C获得了这一行#现在可以了!