是什么在ASP.NET显示缩略图的最佳方法?
-
09-09-2019 - |
题
我创建ASP.NET中的一个普通的画廊,但我有创建缩略图的小经验。我所知道的算法和GetThumbnailImage方法,但我的问题是其他地方 - 我目前显示的图像(只是调整)使用ImageButton控件。而这一点 - 我不知道如何连接的“缩略图”图像ImageUrl属性。它甚至有可能,如果是,怎么样?或者我应该使用一些其他的控制呢?感谢您的任何建议!
解决方案
您可以创建一个HttpHandler的用来处理图像的请求,并返回缩略图(或做任何你需要的图片)。
当你在ASP.NET做图形的东西,记住,几乎的所有的System.Drawing中的是GDI +和thetrefore的包装保存需要被妥善处置非托管内存引用(使用在using
语句)。即使对于简单的类等的StringFormat等也是如此。
其他提示
这听起来像你需要建立一个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方法创建缩略图,但你提到已经采取的这种关心了。您还需要确保你传输文件到浏览器的时候正确设置标头。
HTTP处理器是要走的途径。
上性能的另一注:操作图像是相对昂贵的磁盘空间,无论从存储器和CPU的观点来看。因此从一个完整的图像生成缩略图是你只需要为每个完整的图像做一次。做到这一点的最佳时间大概是在图像上载的时间,特别是如果你将被显示在同一页面上的一些这些。
不隶属于 StackOverflow