Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - MVC3/Razor thumbnail/resize image ideas?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...