2009-11-03 107 views
4

我创建一个图像,其中包含一些文本,对于每个客户,图像包含它们的名称,我使用Graphics.DrawString函数来即时创建,但我不需要不止一次地创建这个映像,只是因为客户的名字应该不会改变,但我不想将它存储在磁盘上。缓存HTTP处理程序.ashx输出

现在我在处理程序即创建图像:

<asp:Image ID="Image1" runat="server" ImageUrl="~/imagehandler.ashx?contactid=1" /> 

什么是缓存自带的影像的最佳方式?我应该缓存它创建的位图吗?或缓存我传回的流?我应该使用哪个缓存对象,我认为有很多不同的方法?但输出缓存不适用于http处理程序?推荐的方式是什么? (我不关心缓存在客户端,我在服务器端)谢谢!

+0

您能否提供更多的信息:您期望的负载类型?以及缓存数据的大小是多少 – Basic 2009-11-08 21:12:43

回答

5

我能想到的最简单的办法是只缓存在HttpContext.Cache位图对象您在图像处理程序创建之后。

private Bitmap GetContactImage(int contactId, HttpContext context) 
{ 
    string cacheKey = "ContactImage#" + contactId; 
    Bitmap bmp = context.Cache[cacheKey]; 

    if (bmp == null) 
    { 
     // generate your bmp 
     context.Cache[cacheKey] = bmp; 
    } 

    return bmp; 
} 
+0

这对我来说工作得非常好。我想缓存的图像是磁盘上文件的缩放版本。如果基本映像文件发生更改,我想基于此缓存映像的缓存。我发现,通过将图像添加到与文件都依赖缓存完美工作:context.Cache.Insert(cacheKey,BMP,新System.Web.Caching.CacheDependency(映像文件名称))//这里的“映像文件名称”指出,在原始文件 – RobbieCanuck 2010-08-20 23:03:56

+0

这将是更好的位图保存到一个MemoryStream和高速缓存,而不是..·1/10的内存使用情况,以及更好的性能。无论如何,将Bitmap实例编码到流中大部分是CPU使用率 - 缓存Bitmap不会优化瓶颈。 @Robbie,如果你缩放图像,看http://imageresizing.net/,磁盘缓存是要走的路。 – 2011-10-28 22:14:58

1

大卫,

你可以处理程序的输出缓存。不是声明式的,而是在代码背后。 看看你是否可以使用下面的代码片段。

 
TimeSpan refresh = new TimeSpan(0, 0, 15); 
HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.Add(refresh)); 
HttpContext.Current.Response.Cache.SetMaxAge(refresh); 
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Server); 
HttpContext.Current.Response.Cache.SetValidUntilExpires(true); 

//try out with – a simple handler which returns the current time 

HttpContext.Current.Response.ContentType = "text/plain"; 
HttpContext.Current.Response.Write("Hello World " + DateTime.Now.ToString("HH:mm:ss")); 
+5

这看起来像浏览器缓存,而不是输出缓存。 – 2010-10-06 18:51:03

+1

仍然是一个非常有用的代码块 – jvenema 2012-06-28 14:13:22