c# - 在缓存中存储图像

标签 c# asp.net caching gdi

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

我不知道是我将图像错误地插入到缓存中还是以错误的方式检索它。如果我尝试使用该流,我会一直收到缓冲区空值。

有什么想法吗?

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

最佳答案

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

仅在将其从缓存中移除之前(如果您需要将其从缓存中移除)或仅在过期时间执行 Dispose 调用。

关于c# - 在缓存中存储图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448990/

相关文章:

c# - 绑定(bind)在 Mvvm wpf 和 controltab 中不起作用

c# - 提高当前 Linq 查询的时间复杂度

asp.net - 如何从时间线中隐藏使用 Graph API 创建的事件

c - 刷新 Linux 内核模块中的 CPU 数据缓存

mysql - 高流量下的 Varnish 高数据库连接

c# - 厚壁二维迷宫中的碰撞检测

c# - ListView 项目上的删除按钮

ASP.NET - 没有 JavaScript 的客户端

asp.net - session 最佳实践

java - 如何实现服务器端分页结果不可预测