29

I'm trying the following code to output a image from a asp.net web api, but the response body length is always 0.

public HttpResponseMessage GetImage()
{
    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StreamContent(new FileStream(@"path to image"));
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return response;
}

Any tips?

WORKS:

    [HttpGet]
    public HttpResponseMessage Resize(string source, int width, int height)
    {
        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();

        // Photo.Resize is a static method to resize the image
        Image image = Photo.Resize(Image.FromFile(@"d:\path\" + source), width, height);

        MemoryStream memoryStream = new MemoryStream();

        image.Save(memoryStream, ImageFormat.Jpeg);

        httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());

        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        httpResponseMessage.StatusCode = HttpStatusCode.OK;

        return httpResponseMessage;
    }
lolol
  • 4,287
  • 3
  • 35
  • 54

2 Answers2

5

The the following:

  1. Ensure path is correct (duh)

  2. Ensure your routing is correct. Either your Controller is ImageController or you have defined a custom route to support "GetImage" on some other controller. (You should get a 404 response for this.)

  3. Ensure you open the stream:

    var stream = new FileStream(path, FileMode.Open);

I tried something similar and it works for me.

Daniel Miller
  • 331
  • 1
  • 2
  • 9
2

Instead of a ByteArrayContent you can also use a StreamContent class to work more efficient with streams.

Gertjan
  • 519
  • 4
  • 5