2009-04-16 130 views
2

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

回答

5

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

每当你在ASP.NET做图形的东西,记住,几乎System.Drawing中的所有是GDI +的包装和thetrefore持有需要被妥善处置非托管内存引用(使用using语句) 。即使对于像StringFormat这样简单的类也是如此。

+0

非常感谢,我会尝试一下! – jkottnauer 2009-04-16 19:05:32

+1

请确保您缓存图像,因为这可能不会缩放所有的图像...... – 2009-04-16 19:44:07

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

Http Handler是要走的路。

有关性能的另一个注意事项:从内存和cpu的角度来看,操作映像相对于磁盘空间都很昂贵。因此,从完整图像生成缩略图是每个完整图像只需执行一次的操作。最好的时间可能是在图片上传的时候,特别是如果你将在同一页面上显示一些图片。

相关问题