Asp.net-Mvc-3
MVC3/Razor 縮略圖/調整圖像大小的想法?
在 MVC3/Razor 中是否有一種簡單而動態的方法來創建縮略圖和調整圖像大小?幫手,圖書館,什麼?
如果我能以某種方式管理來自控制器的圖像大小,那就太好了。甚至在razorview。範例:在索引視圖中,我希望圖像具有一定的尺寸,但在詳細資訊視圖中,我希望它們是全尺寸的。
我知道這個問題含糊不清,但除了舊的 mvc1 thingos 之外,我真的在 google/stackoverflow 上找不到任何東西。
大家一般是怎麼處理的呢?
在 MVC3/Razor 中是否有一種簡單而動態的方法來創建縮略圖和調整圖像大小?幫手,圖書館,什麼?
您可以使用內置的 System.Drawing 程序集和 Image 類來實現這一點。您可以編寫一個控制器操作,該操作將作為參數傳遞圖像名稱和所需的新大小,此控制器操作將執行調整大小並返回新圖像。
例如:
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"); } }現在繼續並在您的視圖中包含此操作:
<img src="@Url.Action("Thumbnail", "SomeController", new { width = 100, height = 50 })" alt="thumb" />
使用
WebImage進來的類System.Web.Helpers.WebImage可以實現這一點。您可以使用這個偉大的孩子即時輸出調整大小的圖像。
範常式式碼:
public void GetPhotoThumbnail(int realtyId, int width, int height) { // Loading photos’ info from database for specific Realty... var photos = DocumentSession.Query<File>().Where(f => f.RealtyId == realtyId); if (photos.Any()) { var photo = photos.First(); new WebImage(photo.Path) .Resize(width, height, false, true) // Resizing the image to 100x100 px on the fly... .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage) .Write(); } // Loading a default photo for realties that don't have a Photo new WebImage(HostingEnvironment.MapPath(@"~/Content/images/no-photo100x100.png")).Write(); }在一個視圖中,你會有這樣的東西:
<img src="@Url.Action("GetPhotoThumbnail", new { realtyId = item.Id, width = 100, height = 100 })" />更多相關資訊:使用 ASP.NET MVC 動態調整圖像大小
WebImage我剛剛在 ASP.NET 站點上找到了這個不錯的教程: