wolfgang ziegler


„make stuff and blog about it“

MVC Controllers returning Images

November 30, 2012

Similar to my post “MVC Controllers returning Text or XML” this post explains how to return an image from an an ASP.NET MVC Controller without creating a dedicated View for it.

The method File provided by the Controller class handles that scenario and creates a FileContentResult (derived from ActionResult) for you.

   1: public class HomeController : Controller
   2: {
   3:   public ActionResult Index()
   4:   {
   5:     var image = new Bitmap(100, 100);
   6:     using (var g = Graphics.FromImage(image))
   7:     {
   8:       g.Clear(Color.LightGreen);
   9:       var redBrush = new SolidBrush(Color.DarkRed);
  10:       g.DrawString("MVC rocks!", SystemFonts.IconTitleFont, redBrush, 0, 0);
  11:     }
  12:     var ms = new MemoryStream();
  13:     image.Save(ms, ImageFormat.Png);
  14:     return File(ms.ToArray(), "image/png");
  15:   }
  16: }

The image on this screenshot is dynamically generated with the code snippet above.

image Quite simple – quite effective.