Is there an easy and dynamic way to create thumbnails and resize images in MVC3/Razor? A helper, libary, anything?
It would be nice, if I somehow could manage the size of the images from the controller. Or even in razorview. Example: In the index view I want the images to be a certain size, but in the details view i want them to be full size.
I know this question is vague, but I really couldnt find anything on google/stackoverflow other than old mvc1 thingos.
How do you guys normally deal with this?
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" />