from stream - Can an ASP.NET MVC controller return an Image?

7 Answers

Using the release version of MVC, here is what I do:

[OutputCache(CacheProfile = "CustomerImages")]
public FileResult Show(int customerId, string imageName)
    var path = string.Concat(ConfigData.ImagesDirectory, customerId, "\\", imageName);
    return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");

I obviously have some application specific stuff in here regarding the path construction, but the returning of the FileStreamResult is nice and simple.

I did some performance testing in regards to this action against your everyday call to the image (bypassing the controller) and the difference between the averages was only about 3 milliseconds (controller avg was 68ms, non-controller was 65ms).

I had tried some of the other methods mentioned in answers here and the performance hit was much more dramatic... several of the solutions responses were as much as 6x the non-controller (other controllers avg 340ms, non-controller 65ms).

core database display

Can I create a Controller that simply returns an image asset?

I would like to route this logic through a controller, whenever a URL such as the following is requested:

The controller will look up topbanner.png and send that image directly back to the client.

I've seen examples of this where you have to create a View - I don't want to use a View. I want to do it all with just the Controller.

Is this possible?

This might be helpful if you'd like to modify the image before returning it:

public ActionResult GetModifiedImage()
    Image image = Image.FromFile(Path.Combine(Server.MapPath("/Content/images"), "image.png"));

    using (Graphics g = Graphics.FromImage(image))
        // do something with the Graphics (eg. write "Hello World!")
        string text = "Hello World!";

        // Create font and brush.
        Font drawFont = new Font("Arial", 10);
        SolidBrush drawBrush = new SolidBrush(Color.Black);

        // Create point for upper-left corner of drawing.
        PointF stringPoint = new PointF(0, 0);

        g.DrawString(text, drawFont, drawBrush, stringPoint);

    MemoryStream ms = new MemoryStream();

    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

    return File(ms.ToArray(), "image/png");

You can write directly to the response but then it isn't testable. It is preferred to return an ActionResult that has deferred execution. Here is my resusable StreamResult:

public class StreamResult : ViewResult
    public Stream Stream { get; set; }
    public string ContentType { get; set; }
    public string ETag { get; set; }

    public override void ExecuteResult(ControllerContext context)
        context.HttpContext.Response.ContentType = ContentType;
        if (ETag != null) context.HttpContext.Response.AddHeader("ETag", ETag);
        const int size = 4096;
        byte[] bytes = new byte[size];
        int numBytes;
        while ((numBytes = Stream.Read(bytes, 0, size)) > 0)
            context.HttpContext.Response.OutputStream.Write(bytes, 0, numBytes);

UPDATE: There are better options than my original answer. This works outside of MVC quite well but it's better to stick with the built-in methods of returning image content. See up-voted answers.

You certainly can. Try out these steps:

  1. Load the image from disk in to a byte array
  2. cache the image in the case you expect more requests for the image and don't want the disk I/O (my sample doesn't cache it below)
  3. Change the mime type via the Response.ContentType
  4. Response.BinaryWrite out the image byte array

Here's some sample code:

string pathToFile = @"C:\Documents and Settings\some_path.jpg";
byte[] imageData = File.ReadAllBytes(pathToFile);
Response.ContentType = "image/jpg";

Hope that helps!

Look at ContentResult. This returns a string, but can be used to make your own BinaryResult-like class.

if (!System.IO.File.Exists(filePath))
    return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception
    return new FilePathResult(filePath, contentType);

SomeHelper.EmptyImageResult() should return FileResult with existing image (1x1 transparent, for example).

This is easiest way if you have files stored on local drive. If files are byte[] or stream - then use FileContentResult or FileStreamResult as Dylan suggested.

You could use the HttpContext.Response and directly write the content to it (WriteFile() might work for you) and then return ContentResult from your action instead of ActionResult.

Disclaimer: I have not tried this, it's based on looking at the available APIs. :-)