How to return an image as the response in ASP.NET

2019-02-26 22:53发布

问题:

how i can cast the http handler response to image.
I have created a handler which gives as follow which does some manipulation in the image


var absolutePath = context.Server.MapPath(imagePath);
var originalImage = Image.FromFile(absolutePath);
originalImage = new ImageMethods().AddWatermarkText(originalImage, "One Click");
context.Response.ContentType = "image/jpeg";
originalImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);   

回答1:

The cast must be binary i.e byte array.

I think you are looking for something like this in handler

    public void ProcessRequest (HttpContext context)
    {
        context.Response.ContentType = "text/image"; ;
        System.IO.Stream strm = ShowImage(Number);


        if (strm != null)
        {
           byte[] buffer = new byte[100000];
           strm.Read(buffer, 0, buffer.Length);
           context.Response.OutputStream.Write(buffer, 0, buffer.Length);
        }
    }