Is there an easy and dynamic way to create thumbnails and resize
images in MVC3/Razor? A helper, libary, anything?
You could use the built-in System.Drawing assembly and the Image class to achieve this. You may write a controller action which would be passed as arguments the image name and the desired new size and this controller action would perform the resize and return the new image.
For example:
public ActionResult Thumbnail(int width, int height)
{
// TODO: the filename could be passed as argument of course
var imageFile = Path.Combine(Server.MapPath("~/app_data"), "test.png");
using (var srcImage = Image.FromFile(imageFile))
using (var newImage = new Bitmap(width, height))
using (var graphics = Graphics.FromImage(newImage))
using (var stream = new MemoryStream())
{
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(srcImage, new Rectangle(0, 0, width, height));
newImage.Save(stream, ImageFormat.Png);
return File(stream.ToArray(), "image/png");
}
}
Now go ahead and include this action in your view:
<img src="@Url.Action("Thumbnail", "SomeController", new { width = 100, height = 50 })" alt="thumb" />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…