How should I return an Image from a controller action c# asp.net-mvc-2?
Asked Answered
V

1

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?

Vedis answered 10/5, 2011 at 16:9 Comment(0)
A
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.

Artificiality answered 10/5, 2011 at 16:12 Comment(6)
@Slaks: Thanks for your response. So how can i can consume this in javascript?Vedis
Provide JavaScript the path to your action which returns the image and handle the result as you would any other image request.Wangle
Do you mean: return new FileContentResult(byteArray, "image/png");Approximate
@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?thanksVedis
@Nathan Taylor: Actually I have figured it out. Stupid me. I get what you mean now thanks.Vedis
@Lee, @Shane: My mistake; I meant File. Fixed.Artificiality

© 2022 - 2024 — McMap. All rights reserved.