Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从缓存中获取位图_C#_Asp.net_Caching_Gdi+ - Fatal编程技术网

C# 从缓存中获取位图

C# 从缓存中获取位图,c#,asp.net,caching,gdi+,C#,Asp.net,Caching,Gdi+,每当我试图从上下文中缓存位图时,我都会得到一个参数异常。位图是从缓存对象强制转换的,但其内容已损坏 异常将在该行中抛出 ImageFormat imageFormat = bitmap.RawFormat; bitmap.RawFormat'引发了类型为'System.ArgumentException'的异常 这只给了我消息“参数无效” 当我在代码中插入断点时,请查看从缓存创建的位图,所有属性都会报告相同的异常 这是我的处理程序发出的流程请求 /// <summary>

每当我试图从上下文中缓存位图时,我都会得到一个参数异常。位图是从缓存对象强制转换的,但其内容已损坏

异常将在该行中抛出

ImageFormat imageFormat = bitmap.RawFormat;
bitmap.RawFormat'引发了类型为'System.ArgumentException'的异常

这只给了我消息“参数无效”

当我在代码中插入断点时,请查看从缓存创建的位图,所有属性都会报告相同的异常

这是我的处理程序发出的流程请求

    /// <summary>
    /// Processes the image request.
    /// </summary>
    /// <param name="context">The httpContext handling the request.</param>
    public void ProcessRequest(HttpContext context)
    {
        //write your handler implementation here.
        if (!string.IsNullOrEmpty(context.Request.QueryString["file"]))
        {
            string file = context.Request.QueryString["file"];
            bool thumbnail = Convert.ToBoolean(context.Request.QueryString["thumb"]);
            // Throw in some code to check width and height.
            int width = Convert.ToInt32(context.Request.QueryString["width"]);
            int height = Convert.ToInt32(context.Request.QueryString["height"]);

            // Store our context key.
            string key = file;

            // Strip away our cache data value.
            file = file.Substring(0, file.LastIndexOf("_", StringComparison.OrdinalIgnoreCase));

            OnServing(file);

            try
            {
                //Check the cache for a file.
                Bitmap bitmap = (Bitmap)context.Cache[key];
                if (bitmap != null)
                {
                    ImageFormat imageFormat = bitmap.RawFormat;
                    // We've found something so lets serve that.
                    using (MemoryStream ms = new MemoryStream())
                    {
                        bitmap.Save(ms, imageFormat);
                        context.Response.BinaryWrite(ms.ToArray());
                    }

                }
                else
                {
                    // Nothing found lets create a file.
                    // Lock the file to prevent access errors.
                    lock (this.syncRoot)
                    {
                        string path = HostingEnvironment.MapPath(String.Format("~/Images/{0}", file));
                        FileInfo fi = new FileInfo(path);
                        if (fi.Exists)
                        {
                            using (Bitmap img = (Bitmap)Bitmap.FromFile(path))
                            {
                                ImageFormat imageFormat = img.RawFormat;
                                if (thumbnail)
                                {
                                    ImageEditor imageEditor = new ImageEditor(img);
                                    Size size = new Size(width, height);
                                    imageEditor.Resize(size, true);
                                    imageEditor.FixGifColors();

                                    using (MemoryStream ms = new MemoryStream())
                                    {
                                        imageEditor.Image.Save(ms, imageFormat);

                                        // Add the file to the cache.
                                        context.Cache.Insert(key, img, new System.Web.Caching.CacheDependency(path));
                                        imageEditor.Dispose();
                                        context.Response.BinaryWrite(ms.ToArray());
                                    }
                                }
                                else
                                {
                                    using (MemoryStream ms = new MemoryStream())
                                    {
                                        img.Save(ms, imageFormat);

                                        // Add the file to the cache.
                                        context.Cache.Insert(key, img, new System.Web.Caching.CacheDependency(path));
                                        context.Response.BinaryWrite(ms.ToArray());
                                    }
                                }
                                OnServed(file);
                            }
                        }
                        else
                        {
                            OnBadRequest(file);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
                // OnBadRequest(ex.Message);
                // return a default empty file here.                    
            }

        }

    }
//
///处理图像请求。
/// 
///处理请求的httpContext。
公共void ProcessRequest(HttpContext上下文)
{
//在这里编写处理程序实现。
如果(!string.IsNullOrEmpty(context.Request.QueryString[“文件”]))
{
字符串文件=context.Request.QueryString[“文件”];
bool-thumbnail=Convert.ToBoolean(context.Request.QueryString[“thumb”]);
//输入一些代码来检查宽度和高度。
int width=Convert.ToInt32(context.Request.QueryString[“width”]);
int height=Convert.ToInt32(context.Request.QueryString[“height”]);
//存储上下文键。
字符串键=文件;
//去掉缓存数据值。
file=file.Substring(0,file.LastIndexOf(“”,StringComparison.OrdinalIgnoreCase));
在线服务(文件);
尝试
{
//检查缓存中的文件。
位图位图=(位图)上下文.Cache[key];
if(位图!=null)
{
ImageFormat ImageFormat=位图.RawFormat;
//我们找到了一些东西,让我们一起来吧。
使用(MemoryStream ms=new MemoryStream())
{
位图.保存(ms,imageFormat);
context.Response.BinaryWrite(ms.ToArray());
}
}
其他的
{
//找不到任何内容,请创建文件。
//锁定文件以防止访问错误。
锁定(this.syncRoot)
{
string path=HostingEnvironment.MapPath(string.Format(“~/Images/{0}”,file));
FileInfo fi=新的FileInfo(路径);
如果(fi.存在)
{
使用(位图img=(位图)Bitmap.FromFile(路径))
{
ImageFormat ImageFormat=img.RawFormat;
如果(缩略图)
{
ImageEditor ImageEditor=新的ImageEditor(img);
尺寸=新尺寸(宽度、高度);
imageEditor.Resize(大小,true);
imageEditor.fixGifColor();
使用(MemoryStream ms=new MemoryStream())
{
imageEditor.Image.Save(ms,imageFormat);
//将文件添加到缓存中。
context.Cache.Insert(key,img,new System.Web.Caching.CacheDependency(path));
Dispose();
context.Response.BinaryWrite(ms.ToArray());
}
}
其他的
{
使用(MemoryStream ms=new MemoryStream())
{
图像保存(ms,图像格式);
//将文件添加到缓存中。
context.Cache.Insert(key,img,new System.Web.Caching.CacheDependency(path));
context.Response.BinaryWrite(ms.ToArray());
}
}
服务(档案);
}
}
其他的
{
OnBadRequest(文件);
}
}
}
}
捕获(例外情况除外)
{
掷骰子;
//OnBadRequest(例如消息);
//在此处返回默认的空文件。
}
}
}

非常感谢您的帮助。

当您将正在使用的图像对象缓存到using块中时:

using (Bitmap img = (Bitmap)Bitmap.FromFile(path))
{
    // ... lots of code

    // Add the file to the cache.
    context.Cache.Insert(key, img, new System.Web.Caching.CacheDependency(path));

    // ... other code
}
在这个using块的末尾,您的位图将被释放。所以你不能再使用它了。如果要从缓存中再次使用位图,则需要停止处理位图


但是,如果缓存了相同的图像,您只想再次返回该图像,那么只缓存MemoryStream可能会更简单、更高效-这不会受到任何不可见的GDI+限制,并且可以在缓存命中时几乎不进行任何处理就返回该图像。

我建议不要将资源保留超过所需的时间

对于上面的代码,问题是当您获得保存的图像时,您并没有创建新的位图-您正在从缓存中检索一个现有的位图,该位图可能已经被处理。请尝试使用以下选项:

// When saving to the cache, use a MemoryStream to save off the bitmap as an array of bytes
using (MemoryStream ms = new MemoryStream()) {
    bitmap.Save(ms, bitmap.RawFormat);
    context.Cache.Insert(key, (byte[])ms.ToArray(), ...
    ...
}

...

// When retrieving, create a new Bitmap based on the bytes retrieved from the cached array
if (context.Cache[key] != null) {
    using (MemoryStream ms = new MemoryStream((byte[])context.Cache[key])) {
        using (Bitmap bmp = new Bitmap(ms)) {
            bmp.Save(context.Response.OutputStream ...
...

你能公布例外情况的具体细节吗?它显示哪一行以及异常的消息是什么?我已经用异常详细信息更新了问题。这似乎没有解决它。我更改了代码并清除了缓存,但仍然得到相同的错误