I put together the following method, which calls my repository to get an image (returned as Linq.Binary). It then writes the byte array to the OutputStream and sets the content type:
public EmptyResult GetImage(int id)
{
Byte[] imageBytes = _repository.GetImage(id).ToArray();
Response.OutputStream.Write( imageBytes, 0, imageBytes.Length);
Response.ContentType = "image/png";
return new EmptyResult();
}
This is one of those times where I wrote a block of code, it worked first try (always scary), and now I'm trying to think through where it will break.
My requirements are just to return an image that I'm getting from the database, no text.
What I'm doing above allows me to avoid the use of converting to a Bitmap (or other Image type), I don't need to have references to System.Drawing, I don't need to write a custom ActionResult and I don't need to worry about disposing resources.
I'd have to think a little further through, but I think this also opens the door to leveraging the MVC OutputCache without much pain.
I see people writing custom ActionResults and am trying to figure out the benefit. I mean, I understand the additional flexibility and ability to handle multiple types, but one solution I found took the Binary.ToArray(), converted to a Bitmap and created an ashx handler to return the image. Is any of that necessary?
Is it bad form to write to the output stream when you're returning an EmptyResult?
In all current browsers, the above code allows me to display an image with a simple:
<img id="display-image"
src="<%= Url.Action("GetImage", new { id = Model.ImageID }) %>" />
So are their downfalls to this approach?
Thanks for thoughts/comments folks.
Cheers, -james