Dan*_* T. 11 asp.net-mvc resize image-manipulation image dynamic
如何在ASP.NET MVC中动态调整图像大小?
我正在尝试从服务器上已有的图像自动创建缩略图.在ASP.NET Webforms中,我创建了一个HTTPHandler来执行此操作并在web.configfor for all images扩展中添加动词以通过处理程序.处理程序很好,如果你想要原始图像,你可以使用一个典型的图像标记:
<img src="pic.jpg"/>
但如果你想要一个调整大小的图像,你可以使用:
<img src="pic.jpg?width=320&height=240"/>
有没有办法在ASP.NET MVC中复制相同的行为?
Len*_*rri 12
使用你的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();
}
Run Code Online (Sandbox Code Playgroud)
在一个视图中你有这样的东西:
<img src="@Url.Action("GetPhotoThumbnail",
new { realtyId = item.Id, width = 100, height = 100 })" />
Run Code Online (Sandbox Code Playgroud)
更多关于它:使用ASP.NET MVC动态调整图像大小
ASP.NET网站上还有一个很棒的教程:在ASP.NET网页(Razor)站点中使用图像.
您绝对可以重复使用相同的IHttpHandler。您只需要一个新的IRouteHandler将传入请求映射到正确的处理程序:
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new YourImageHttphandler();
}
}
Run Code Online (Sandbox Code Playgroud)
在您的路线中,添加:
routes.Add("Images", new Route("images/{*file}", new ImageRouteHandler()));
Run Code Online (Sandbox Code Playgroud)
现在/images(eg /images/pic.jpg?width=320&height=240) 中的任何请求都将由您现有的处理程序处理。显然,您可以更改路由模式以匹配任何有意义的路径,就像典型的 MVC 路由一样。
| 归档时间: |
|
| 查看次数: |
16073 次 |
| 最近记录: |