当处理非常大的图像时,如何避免位图内存不足:即10.000.000像素及以上

thi*_*lam 18 c# system.drawing bitmap

目前我正在开发一个加载非常大的图像的系统,最小宽度x高度= = 10.000.000像素.

但是用户上传图像的比例通常与我们的要求比率不匹配,因此我必须将其裁剪为适当的比例,但是当使用System.Drawing位图裁剪它时,我总是得到SytemOutOfMemory异常.

我尝试使用正确的RectangleF但没有运气的Bitmap.Clone和Graphic.DrawImage.

反正有没有得到outofmemory异常,或者System.Drawing库有什么替代方法可以轻松完成这项任务吗?

我的代码从用户上传文件加载图像:

    var fileBinary = new byte[stream.Length];
    stream.Read(fileBinary, 0, fileBinary.Length);
    stream.Position = 0;
    var fileExtension = Path.GetExtension(fileName);
    using (Image image = Image.FromStream(stream, false, false))
    {
        //validation and check ratio
        CropImage(image, PORTRAIT_RATIO, fileExtension);
     }
Run Code Online (Sandbox Code Playgroud)

而CropImage功能:

//Crop Image from center with predefine ratio
    private byte[] CropImage(Image sourceImg, float ratio, string fileExtension)
        var height = sourceImg.Height;
        var width = sourceImg.Width;

        var isPortrait = width < height;
        RectangleF croppingRec = new RectangleF();

        float positionX = 0;
        float positionY = 0;
        float cropHeight = (float)height;
        float cropWidth = cropHeight * PORTRAIT_RATIO;
        positionY = 0;
        positionX = (width - cropWidth) / 2;

        if (cropWidth > width)
        {
            cropWidth = width;
            cropHeight = cropWidth * (1 / PORTRAIT_RATIO);
            positionX = 0;
            positionY = ((height - cropHeight) / 2);

        }

        croppingRec.Width = cropWidth;
        croppingRec.Height = cropHeight;
        croppingRec.X = positionX;
        croppingRec.Y = positionY;

        Bitmap bmpImage = sourceImg as Bitmap;
        Bitmap bmpCrop = bmpImage.Clone(croppingRec, bmpImage.PixelFormat);
        bmpCrop.Save("D:/test" + fileExtension, ImageFormat.Jpeg);

        ImageConverter converter = new ImageConverter();

        return (byte[])converter.ConvertTo(bmpCrop, typeof(byte[]));
    }

}
Run Code Online (Sandbox Code Playgroud)

Tod*_*odd 0

尝试使用graphicsmagick.net库,然后使用MagickImage上的Crop方法。它应该仍然可以在 asp.net 下正常工作,并使用磁盘临时处理巨大的图像文件。