我们在ASP.NET MVC3中有图像上传的场景。
public ActionResult Upload(IEnumerable<HttpPostedFileBase> images, SomeViewModel model)
{
foreach(var i in images)
{
...
byte[] fileBytes = i.InputStream.GetBytesArray();
byte[] image = _imageManager.Resize(fileBytes, MaxImageWidth, MaxImageHeight, true);
...
}
}
public byte[] Resize(byte[] content, int width, int height, bool preserveAR = true)
{
if (content == null)
return null;
WebImage wi = new WebImage(content);
wi = wi.Resize(width, height, preserveAspectRatio);
return wi.GetBytes();
}
因此,我们从客户端收到的图像为HttpPostedFileBase。我们将byte [] fileBytes传递给imageManager的Resize方法。图像管理器正在创建新的WebImage实例,然后调整图像大小并再次将其转换为byte []。
在调试此代码时,此刻我通过wi.GetBytes()行,我的内存使用量急剧增加(至少500mb)。我正在上传10mb的图片。当上传较小尺寸的照片(〜1.5mb)时,内存消耗是正常的。
这可能是什么原因,并且可以通过某种方式解决?
谢谢
最佳答案
在后台,WebImage使用System.Drawing.Image.FromStream
来获取原始图像流并将其转换为字节数组。我尝试拍摄一个6.0MB的JPG并在其上调用该方法,然后得到其中包含6.0MB的流。如果我要求BMP,我会收到172MB字节的请求
我怀疑您正在上传压缩图像(例如PNG / JPG),并且对GetBytes的调用导致该图像的解压缩字节可用。解压缩为原始格式后,图像实际上可能会更大。要解决整个流对象不足的问题,您可以做的事情并不多,因此您永远不会将所有内容立即加载到内存中。
关于asp.net - WebImage和大量内存消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899411/