在ASP.NET中显示缩略图的最佳方法是什么?

时间:2009-04-16 18:56:16

标签: c# asp.net image thumbnails imagebutton

我正在ASP.NET中创建一个常规库,但我没有创建缩略图的经验。我知道算法和GetThumbnailImage方法,但我的问题是在其他地方 - 我正在使用ImageButton控件显示图像(刚刚调整大小)。这就是重点 - 我不知道如何将“缩略图”图像连接到ImageUrl属性。甚至是可能的,如果是的话,怎么样?或者我应该使用其他控件吗?谢谢你的任何建议!

3 个答案:

答案 0 :(得分:6)

听起来你需要设置一个HttpHandler,它可以创建调整大小的图像,也可以将它缓存到磁盘上,以节省每个请求上重新创建缩略图的时间。

所以,例如:

<asp:ImageButton ID="ImageButton1" ImageUrl="~/ImageHandler.ashx?ImageId=123" runat="server />

然后你会有一个处理程序:

namespace MyProject
{
    public class ImageHandler : IHttpHandler
    {
        public virtual void ProcessRequest(HttpContext context)
        {
            // 1. Get querystring parameter
            // 2. Check if resized image is in cache
            // 3. If not, create it and cache to disk
            // 5. Send the image

            // Example Below
            // -------------

            // Get ID from querystring
            string id = context.Request.QueryString.Get("ImageId");

            // Construct path to cached thumbnail file
            string path = context.Server.MapPath("~/ImageCache/" + id + ".jpg");

            // Create the file if it doesn't exist already
            if (!File.Exists(path))
                CreateThumbnailImage(id);

            // Set content-type, content-length, etc headers

            // Send the file
            Response.TransmitFile(path);
        }

        public virtual bool IsReusable
        {
            get { return true; }
        }
    }
}

您还需要在web.config

中进行设置
<system.web>
    <httpHandlers>
        <add verb="*" path="ImageHandler.ashx" type="MyProject.ImageHandler, MyProject"/>
    </httpHandlers>
</system.web>

这应该足以让你入门。您需要修改ProcessRequest方法来创建缩略图,但您提到已经处理过这个问题。您还需要确保在将文件传输到浏览器时正确设置标题。

答案 1 :(得分:5)

您可以创建一个处理图像请求并返回缩略图的HttpHandler(或者对图像执行任何操作)。

每当你在ASP.NET中做图形工作时,请记住,System.Drawing的 all 几乎是GDI +的包装器,并且保留了对需要正确处理的非托管内存的引用(使用using声明。即使对于StringFormat等简单的类也是如此。

答案 2 :(得分:1)

Http Handler是要走的路。

关于性能的另一个注意事项:从内存和CPU的角度来看,操作映像相对于磁盘空间来说是昂贵的。因此,从完整图像生成缩略图是您只想为每个完整图像执行一次。这样做的最佳时间可能是上传图片的时间,特别是如果您要在同一页面上显示其中的一些图片。

相关问题