在缓存中存储图像

时间:2011-12-09 16:59:32

标签: c# asp.net caching gdi

我有一个图像处理程序,但它不断抛出错误

我不知道我是否错误地将图像插入缓存或以错误的方式检索它。如果我尝试使用流,我会一直得到缓冲区null。

任何想法?

public void ProcessRequest(HttpContext context)
    {          
        _imageController = new ImageController();

        //Use ImageUrl to request image from external site
        string imageUrl = CastAide.AsString(context.Request["imageUrl"], String.Empty);
        //Use imageGuid and pageid to get image from user response upload
        string imageGuid = CastAide.AsString(context.Request["image"], String.Empty);
        int pageId = CastAide.AsInt32(context.Request["pageId"], -1);
        string subFolder = CastAide.AsString(context.Request["sub"], String.Empty);
        //Use ImageVaultId to return an imageVault Image
        int imageVaultId = CastAide.AsInt32(context.Request["imageVaultId"], 0);
        //Width and height determine the image size rendered
        int width = CastAide.AsInt32(context.Request["width"], 200);
        int height = CastAide.AsInt32(context.Request["height"], 200);
        bool resizeNoCrop = CastAide.AsBoolean(context.Request["resizeonly"], false);

        string cacheKey = "";
        Bitmap image = null;

    // Generate cache key
    if (!String.IsNullOrEmpty(imageGuid))            
        cacheKey = String.Format("{0}_{1}", imageGuid, "guid");                           
    else if (!String.IsNullOrEmpty(imageUrl))            
        cacheKey = String.Format("{0}_{1}", imageUrl, "url");                              
    else if (imageVaultId > 0)            
        cacheKey = String.Format("{0}_{1}", imageVaultId, "vault");                 

    // Load from cache
    if (context.Cache[cacheKey] != null)
    {           
        // Load from cache
        //MemoryStream ms = new MemoryStream((byte[])context.Cache[cacheKey]);
        //image = (Bitmap)Bitmap.FromStream(ms);
        image = context.Cache[cacheKey] as Bitmap;                             
    }
    else
    {
        if (!String.IsNullOrEmpty(imageGuid))
        {
            // load file from the local file store
            FileInfo fi;

            if (!String.IsNullOrEmpty(subFolder))
                fi = new FileInfo(_imageController.GetFilePath(subFolder, imageGuid));
            else
                fi = new FileInfo(_imageController.GetFilePath(pageId, imageGuid));

            if (fi.Exists)
                image = (Bitmap) Bitmap.FromFile(fi.FullName);
            else
                image = (Bitmap) Bitmap.FromFile(ConfigurationManager.AppSettings["ImageNotFoundPath"]);
        }
        else if (!String.IsNullOrEmpty(imageUrl))
        {
            // load file from the internet
            try
            {
                HttpWebRequest request = (HttpWebRequest) WebRequest.Create(imageUrl);
                WebResponse response = request.GetResponse();
                Stream stream = response.GetResponseStream();
                image = (Bitmap) Bitmap.FromStream(stream);
                response.Close();
            }
            catch
            {
                image = (Bitmap) Bitmap.FromFile(ConfigurationManager.AppSettings["ImageNotFoundPath"]);
            }
        }
        else if (imageVaultId > 0)
        {                   
            string filePath = ImageVaultUtility.GetSourceFileName(imageVaultId);
            FileInfo fi = new FileInfo(filePath);

            if (fi.Exists)                    
                image = (Bitmap) Bitmap.FromFile(fi.FullName);                    
            else                    
                image = (Bitmap) Bitmap.FromFile(ConfigurationManager.AppSettings["ImageNotFoundPath"]);                    
        }

        // Insert image into cache
        context.Cache.Insert(cacheKey, image, null, DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);    
        }


        if (resizeNoCrop)
            ImageUtility.ApplyResizeTransform(ref image, width, height, true);
        else
            ImageUtility.ApplyCropAndResizeTransform(ref image, width, height);

        context.Response.Clear();
        context.Response.ContentType = "image/jpeg";
        image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        image.Dispose();

    }

检索缓存时会发生以下情况:

enter image description here

3 个答案:

答案 0 :(得分:2)

如果要在缓存中保留有效图像,则不应进行image.Dispose()调用。这将基本上释放非托管GDI +资源,但将图像引用保留在缓存中,GDI +将在下次调用时不满意。

只有在从缓存中删除它之前进行Dispose调用(如果需要将其从缓存中删除)或仅在到期时间。

答案 1 :(得分:0)

您可以将此代码用于图像缓存。

http://www.codeproject.com/KB/aspnet/CachingImagesInASPNET.aspx

答案 2 :(得分:0)

默认情况下,创建位图图像时,如果您的应用想要更新或修改图像,图像将被解冻。在封面下,系统还保留了创建位图的线程,并禁止其他线程修改图像。您收到错误,因为多个线程正在尝试访问缓存中的图像。在将其添加到缓存之前,您需要做的是:

if(image.CanFreeze) {
  image.Freeze();
}

这将使文件静态且不可修改,并允许框架将Image传递给其他调用线程而不会出现问题。

要非常小心,因为如果您在没有某种管理的情况下缓存它们,那么拥有许多图像文件的繁忙服务器可能会耗尽内存。