luisgepeto
luisgepeto

Reputation: 813

Return Image type from MVC controller and display

I have an application where the user can select an image via a file input. When the image is selected, I upload the image via AJAX to the controller and convert it to grayscale. The conversion method returns a System.Drawing.Image object. What I want is to return this grayscale image object on the AJAX success function and display it on another div in the same page where the original image was uploaded. Please notice that this image is never stored anywhere, so there is no reason to use a File return action in my controller. What can I do? Greetings Luis.

Upvotes: 1

Views: 942

Answers (2)

Brad Christie
Brad Christie

Reputation: 101604

public class ImageResult : ActionResult
{
    private Image Image { get; private set; }
    private ImageFormat ImageFormat { get; private set; }

    public ImageResult(Image image, ImageFormat imageFormat = ImageFormat.Png)
    {
        if (image == null) throw new ArgumentNullException("image");
        this.Image = image;
        this.ImageFormat = format;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var httpContext = context.HttpContext;

        httpContext.Response.Clear();
        httpContext.Response.ContentType = this.GetContentType();
        this.Image.Save(httpContext.Response.OutputStream, this.ImageFormat);
    }

    private String GetContentType()
    { // borrowed: http://stackoverflow.com/a/15261265/298053
        var imageCodecInfos = ImageCodecInfo.GetImageEncoders();
        var codec = imageCodecInfos.FirstOrDefault(x => x.FormatID == this.ImageFormat.Guid);
        return codec != null ? codec.MimeType : "application/octet-stream";
    }
}

Then, you should be able to do something like:

Image bwImage = /* service call */;
return new ImageResult(bwImage, ImageFormat.Png);

Upvotes: 0

Scott Selby
Scott Selby

Reputation: 9570

what you would do is base64 encode the image and send it back to client , then in the client do something like this in the HTML:

<img src="data:image/png;base64,' + data + '" />

Upvotes: 1

Related Questions