Kas*_*kov 15 image thumbnails image-resizing razor asp.net-mvc-3
有没有一种简单而动态的方法来创建缩略图并在MVC3/Razor中调整图像大小?帮手,图书馆,什么?
如果我能以某种方式管理来自控制器的图像大小,那将是很好的.甚至在razorview.示例:在索引视图中,我希望图像具有特定大小,但在详细信息视图中,我希望它们是完整大小.
我知道这个问题很模糊,但除了旧的mvc1之外,我真的无法在google/stackoverflow上找到任何东西.
你们通常如何对待这个?
Dar*_*rov 25
有没有一种简单而动态的方法来创建缩略图并在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");
}
}
Run Code Online (Sandbox Code Playgroud)
现在继续在您的视图中包含此操作:
<img src="@Url.Action("Thumbnail", "SomeController", new { width = 100, height = 50 })" alt="thumb" />
Run Code Online (Sandbox Code Playgroud)
Len*_*rri 19
使用你的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动态调整图像大小
我刚刚WebImage
在ASP.NET站点上找到了这个很好的教程:
ter*_*tyl 10
另请查看我的Simple.ImageResizer.MvcExtensions nuget包.
演示网站:http://imageresizer.apphb.com/
添加一个ImageResult类,您可以在控制器操作中使用该类,该操作采用高度和宽度输入,这样可以非常轻松地将图像大小调整添加到您的mvc站点.很想听听你的想法
归档时间: |
|
查看次数: |
26709 次 |
最近记录: |