使用位图调整大图像大小的 OutOfMemoryException

OutOfMemoryException using Bitmap to resize large image

我想在我的网站上调整图像的大小,但是当我使用位图加载 14032*19864(png 扩展名)的图像时,抛出 OutOfMemoryException。我的编译器配置是 any cpu。 我在怀疑 运行 环境是不是 x64。 代码如下:

public ActionResult BimDWGViewer()
{
    Viewer.Uri uri = null;
    string url = Request.Params["u"];
    uri = new Viewer.Uri("image@"+url);
    int width = Int32.Parse(Request.Params["w"]);
    int height = Int32.Parse(Request.Params["h"]);
    Nebula.Nexus.Helpers.ModelUriTranslator.TranslateUri(uri);
    if (uri.IsFileProtocol)
    {
        string path = uri.Path;
        System.Drawing.Bitmap image_source = new System.Drawing.Bitmap(path);
        System.Drawing.Bitmap image_result = new System.Drawing.Bitmap(width,height);
        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image_result))
        {
            g.DrawImage(image_source, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, image_source.Width, image_source.Height), System.Drawing.GraphicsUnit.Pixel);
        }
        MemoryStream output = new MemoryStream();
        image_result.Save(output, System.Drawing.Imaging.ImageFormat.Png);
        byte[] res = output.ToArray();
        output.Dispose();
        image_source.Dispose();
        image_result.Dispose();
        return new FileContentResult(res, "image/png");
    }

}

异常发生在

System.Drawing.Bitmap image_source = new System.Drawing.Bitmap(path);

您是否已禁用 "Prefer 32 bit"?

http://www.neovolve.com/2015/07/31/disable-prefer-32-bit/

确保您在配置文件中将 gcAllowVeryLargeObjects 元素设置为 true

.NET 中的单个分配最大为 2 GB(即使 运行 作为 64 位进程)并且您正在使用的 类 之一很可能正在做内部会碰到这个限制的东西。这是一个很常见的问题,修复您的配置文件应该可以解决这个问题。

更新: 根据下面的评论,@majing 运行 遇到的问题是 Visual Studio 正在以 32 位启动他的网络应用程序IIS Express 版本。配置 VS 以将 IIS 作为 64 位进程启动修复了该问题。