2009-11-03 105 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