0

In our ASP.NET MVC 3 We are currently generating thumbnail images on the fly with the following code:

public void GetImageThumbnail(string imageName)
{

   WebImage wbImage = new WebImage("~/assets/images/gallery/"+imageName+".jpg");

   int width = 220;

   wbImage.Resize(width, (int)((double)wbImage.Height * width / wbImage.Width));

   wbImage.FileName = imageName+"_small.jpg";

   wbImage.Write();

}

and displaying them in the view like this:

<img src="@Url.Action("GetImageThumbnail", new {imageName = "motherboard"})" alt="" />

How can we control the image size on the view and generate the complete <img> tag from scratch? We need to specify the image dimension and obtain an <img> tag the contains the width and height properties.

Thanks.

4

1 回答 1

0

我的第一个想法是创建自己的 HTML 辅助方法来完成所有工作。你会吃的东西像:

    @Html.ThumbnailImg("motherboard")

该方法执行缩略图工作并可以输出完整的所需标记。更多信息:http ://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs 。对于它的价值,我更喜欢扩展方法设计。对其他开发人员来说似乎更可口。

更新:有一点我以前没有想到的先有鸡还是先有蛋。也许是这样的:

    public static MvcHtmlString ThumbnailImg(
        this HtmlHelper html,
        UrlHelper url,
        String imageName,
        String elementID,
        String altText)
    {

        var img = new TagBuilder("img");
        if (String.IsNullOrEmpty(elementID) == false) img.MergeAttribute("id", elementID);
        if (String.IsNullOrEmpty(altText) == false) img.MergeAttribute("alt", altText);

        // Generate and cache thumnail here, determining height and width
        // ... 

        var src = url.Action("GetImageThumbnail", new { imageName = imageName });
        img.MergeAttribute("height", height);
        img.MergeAttribute("width", width);

        img.MergeAttribute("src", src);
        return MvcHtmlString.Create(img.ToString(TagRenderMode.SelfClosing));
    }
于 2013-05-28T16:26:21.833 回答