5

I am building images from a byte[] like below.

public FileContentResult GetEmployeeImage(int empId)
{
   MemoryStream ms = new MemoryStream(byteArray);
   Image returnImage = Image.FromStream(ms);
   return returnImage;//How should i return this image to be consumed by javascript.
}

I want to return this image to the browser via a controller action method, so as it can be consumed by my javascript code and displayed in the browser. How should I do this?

shane87
  • 3,090
  • 12
  • 51
  • 65

1 Answers1

10

You don't need to create an image object; you just want to return the raw data.
The browser will read the raw data into an image.

return File(byteArray, "image/png");

Obviously, you need to pass the correct content type, depending on what image format is in the byte array.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • @Slaks: Thanks for your response. So how can i can consume this in javascript? – shane87 May 10 '11 at 16:13
  • 1
    Provide JavaScript the path to your action which returns the image and handle the result as you would any other image request. – Nathan Taylor May 10 '11 at 16:14
  • 2
    Do you mean: return new FileContentResult(byteArray, "image/png"); – Lee Gunn May 10 '11 at 16:15
  • @Slaks: the `return Content(byteArray, "image/png");` expected a string as first parameter. So I took Lee Gunn's advice from above and used `return new FileContentResult(byteArray, "image/png")` is this correct? @Nathan Taylor: Forgive me for being a bit dumb here, but can you provide a short example of what you mean?thanks – shane87 May 10 '11 at 16:21
  • 1
    @Nathan Taylor: Actually I have figured it out. Stupid me. I get what you mean now thanks. – shane87 May 10 '11 at 16:27
  • @Lee, @Shane: My mistake; I meant `File`. Fixed. – SLaks May 10 '11 at 16:48