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

Dav*_*lds 3 c# iis image server

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

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

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

Dav*_*lds 5

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

public static Image ResizeImage(Image imgToResize, Size size)
    {
        return (Image)(new Bitmap(imgToResize, size));
    }
Run Code Online (Sandbox Code Playgroud)

麻烦的代码行现在是:

using(Image thumbnail = ResizeImage(image, new Size(m_thumbnailWidth, thHeight)))
Run Code Online (Sandbox Code Playgroud)

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


ste*_*n.s 5

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

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

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

看评论:

注意事项

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

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