.net在上传时缩小服务器中的图像(如果超过大小限制)

本文关键字:如果 图像 缩小 服务器 net | 更新日期: 2023-09-27 18:25:17

当用户上传文件时,

检查图像宽度/高度是否超过设定限制,并在需要时调整图像大小的最佳方法是什么?

目前,我正在尝试将HttpPostedFileBase保存到临时文件夹中,以便使用Bitmap.FromFile()加载它,只需检查图像的宽度/高度。

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

到目前为止,我在Bitmap.FromFile(path)阶段达到了out of memory exception

.net在上传时缩小服务器中的图像(如果超过大小限制)

ImageResizer 3.4包含了一个新的ImageUploadHelper项目/插件,使其更安全、更容易。(你可以在源下载的/Plugins文件夹中找到它,但它还没有NuGet包,因为它仍在预览中。

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);
}