Question

I'm trying to use ImageResizer which is so far a really good image cropper when I use it directly on an image like so:

<img src="myimage.jpg?height=300" />

But when I'm trying to use a ashx handler to write out the image, I'm experiencing some problems. Here is my code:

ImageHandler.ashx

    string filePath = (HttpContext.Current.Request.PhysicalApplicationPath + context.Session["currentdirectory"]);
    string file = context.Request.QueryString["name"];

    MemoryStream ms = new MemoryStream();

    ImageBuilder.Current.Build(new ImageJob(filePath + "/" + file, ms, new Instructions("height=300"), false, true));


    context.Response.Write(ms.ToArray());
    context.Response.ContentType = "image/jpeg";
    context.Response.AddHeader(
       "Content-Disposition",
       "inline; filename=" + file);

It seems when using above code, the image is broken, or as mozilla firefox says: The image 'myimage.jpg' cannot be shown, because it contains errors.

So I guess that the byte array it gets is apparently wrong?

Do I send a wrong type to Response.Write or am i just using ImageBuilder the wrong way? Or what could be to solution to my problem here?

Edit: Btw writing it to a file instead of memorystream works, so I must do something wrong when trying to write it via handler?

    var to = HttpContext.Current.Request.PhysicalApplicationPath + "/" + file;
    ImageBuilder.Current.Build(new ImageJob(filePath + "/" + file, to, new Instructions("height=300")));
Was it helpful?

Solution

This works for me:

var filePath = HttpContext.Current.Server.MapPath("~/img");
var file = context.Request.QueryString["name"];

using(var ms = new MemoryStream())
{
    ImageBuilder.Current.Build( new ImageJob( filePath + "/" + file, ms, new Instructions( "height=300" ), false, true ) );

    context.Response.ContentType = "image/jpeg";
    context.Response.AddHeader( "Content-Disposition", "inline; filename=" + file );
    ms.WriteTo(context.Response.OutputStream);
}

or just use:

context.Response.BinaryWrite(ms.ToArray());

this works also

OTHER TIPS

does

ImageBuilder.Current.Build(...)

run in an seperate thread? if it does, then this could be the problem, you wrote something to the stream, before the task is finished.

Maybe there is callback or a synchronized method to run the image resizer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top