Reputation: 1963
Here is my code :
HTML : <img src="thumbCreate.ashx?Id=223" alt="asd" />
HTTP Handler : `
public void ProcessRequest (HttpContext context)
{
CreateThumbNail(context);
}
private void CreateThumbNail(HttpContext context)
{
string resourceId = context.Request.QueryString["Id"];
context.Response.Write("No resource found for Id = " + resourceId);
Bitmap original = new Bitmap("C:/Devp/My work/ASHXSampleApp/Images/Desert.jpg");
int oWidth = original.Width;
int oHeight = original.Height;
int preferredWidth = 80;
int preferredHeight = 100;
int thumbWidthFactor = oWidth / preferredWidth;
int thumbHeightFactor = oHeight / preferredHeight;
int maxFactor = Math.Max(thumbWidthFactor, thumbHeightFactor);
int thumbNailWidth = oWidth / maxFactor;
int thumbNailHeight = oHeight / maxFactor;
Bitmap thumbNailImage = (Bitmap)original.GetThumbnailImage(thumbNailWidth, thumbNailHeight, ThumbNailCallback, IntPtr.Zero);
context.Response.ContentType = "image/Jpeg";
thumbNailImage.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}`
But this code does not display image. When I manually try to run the handler in firefox, it gives me an error : - "The image “http://localhost:57157/ASHXSampleApp/thumbCreate.ashx?Id=223” cannot be displayed because it contains errors." Any idea?
Upvotes: 0
Views: 1434
Reputation: 17522
The problem comes from this part of your code.
string resourceId = context.Request.QueryString["Id"];
context.Response.Write("No resource found for Id = " + resourceId);
You are always adding a string to the response stream and then you write the image data afterwards which will result in a corrupted string. Remove that (or make it conditional so it is added when an error occurs or something) and it should work.
Upvotes: 3