.NET上载时缩小在服务器映像如果过去的大小限制 [英] .net scale down images in server upon upload if past size limit

查看:165
本文介绍了.NET上载时缩小在服务器映像如果过去的大小限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户上传文件,

什么是检查图像的宽度/高度超过设置的限制,并根据需要调整图像的最佳方法是什么?

What is the best way to check if the image width / height is over a set limit, and resize the image if needed?

目前,我尝试用保存 HttpPostedFileBase 到一个临时文件夹,以便使用来加载它 Bitmap.FromFile()只是TI检查图像的宽度/高度。

Currently I am experimenting with saving the HttpPostedFileBase to a temp folder in order to load it using Bitmap.FromFile() just ti check the width/height of the image.

然后,使用 ImageResizer 库用来调整图像大小 ImageResizer.ImageJob

Then, use ImageResizer library to resize the image using ImageResizer.ImageJob.

到目前为止,我打内存不够的异常 Bitmap.FromFile(路径)阶段。

So far I am hitting out of memory exception at the Bitmap.FromFile(path) stage.

推荐答案

ImageResizer 3.4包括一个新的ImageUploadHelper项目/插件,使这个更安全,更容易。 (您可以在源码下载的/ plugins文件夹中找到这一点,但还没有一个的NuGet包因为它仍然在preVIEW。

ImageResizer 3.4 includes a new ImageUploadHelper project/plugin to make this safer and easier. (You can find this in the /Plugins folder of the source download, but it doesn't yet have a NuGet package as it's still in preview.

long pixels = 0;

try{
  var size = ImageUploadHelper.GetImageSize(httpPostedFile);
  pixels = size[0] * size[1];
} catch{} //Corrupted images will cause an OutOfMemoryException.

string resultPath = null;
if (pixels > 3 * 1000 * 1000){
  var j = new ImageJob(httpPostedFile,"~/uploads/<guid>.<ext>", new Instructions("maxwidth=1700&maxheight=1700");
  j.Build();
  resultPath = PathUtils.GuessVirtualPath(j.FinalPath);
}else{
  resultPath = "~/uploads/" + ImageUploadHelper.SaveUploadedFileSafely("~/uploads",httpPostedFile);
}

这篇关于.NET上载时缩小在服务器映像如果过去的大小限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆