0

When user uploads file,

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

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.

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

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

Lilith River
  • 16,204
  • 2
  • 44
  • 76
CodeToad
  • 4,656
  • 6
  • 41
  • 53

1 Answers1

0

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);
}
Lilith River
  • 16,204
  • 2
  • 44
  • 76