Whenever I try to get a bitmap I have cached from the context I am getting an argument exception. The bitmap is cast from the cached object but it's contents are corrupted.
The exception is thrown on the line
ImageFormat imageFormat = bitmap.RawFormat;
bitmap.RawFormat' threw an exception of type 'System.ArgumentException'
Which just gives me the message 'Parameter not valid.'
When I stick a breakpoint in the code look at the bitmap created from the cache all the properties report back the same exception.
Here's the process request from my handler....
/// <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.
}
}
}
Any help would be greatly appreciated.