Generating image thumbnails in ASP.NET?
This has done me fine for years:
public static void CreateThumbnail(string filename, int desiredWidth, int desiredHeight, string outFilename){ using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename)) { float widthRatio = (float)img.Width / (float)desiredWidth; float heightRatio = (float)img.Height / (float)desiredHeight; // Resize to the greatest ratio float ratio = heightRatio > widthRatio ? heightRatio : widthRatio; int newWidth = Convert.ToInt32(Math.Floor((float)img.Width / ratio)); int newHeight = Convert.ToInt32(Math.Floor((float)img.Height / ratio)); using (System.Drawing.Image thumb = img.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailImageAbortCallback), IntPtr.Zero)) { thumb.Save(outFilename, System.Drawing.Imaging.ImageFormat.Jpeg); } }}public static bool ThumbnailImageAbortCallback(){ return true;}
For intensive server-side code, I suggest you use other techniques than GDI+ that has not been designed to handle images chunk by chunk (in a streaming manner).
You can use Windows Imaging Component or WPF for this task. There is a very good example on how to do this in a fast and - more important - scalable manner here:
The fastest way to resize images from ASP.NET. And it’s (more) supported-ish.
I use ImageMagick for photo processing
UPDATED
Model:
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.IO;using ImageMagickObject;namespace photostorage.Models{ public class PhotoProcessing { public MagickImage ResizeImg(string filepath, string filename) { Object[] rotate = new Object[] { filepath + "/" + filename, "-auto-orient", filepath + "/" + filename }; Object[] big = new Object[] { filepath + "/" + filename, "-resize", "800", filepath + "/" + "big_" + filename }; Object[] middle = new Object[] { filepath + "/big_" + filename, "-resize", "400", filepath + "/" + "mid_" + filename }; Object[] small = new Object[] { filepath + "/mid_" + filename, "-resize", "200", filepath + "/" + "small_" + filename }; Object[] crop = new Object[] { filepath + "/small_" + filename, "-resize", "50", filepath + "/" + "crop_" + filename }; ImageMagickObject.MagickImage img = new ImageMagickObject.MagickImage(); img.Convert(rotate); img.Convert(big); img.Convert(middle); img.Convert(small); img.Convert(crop); return img; } }}
Controller:
PhotoProcessing resizeImg = new PhotoProcessing();[HttpPost]public string Index(params,params,params...){ var GetResize = resizeImg.ResizeImg( destinationFolder + "/" + curFolder, fullFileName);}