7

I have an object of type System.Drawing.Image and would like to display this image in a view. What would be the best way to do this?

I have found some custom Html Helper methods that might fit the situation. Also found an example that uses a new action method that returns a FileContentResult in order to pull something like this off. I would like to know what technique is best and easiest to implement.

EDIT

To be more specific, I have the image in a System.Drawing.Image variable in the Controller that I want to display in the view.

d456
  • 1,047
  • 3
  • 13
  • 23

1 Answers1

14
public ActionResult GetImg()
{
    string imageFile = System.Web.HttpContext.Current.
                                 Server.MapPath("~/Content/tempimg/unicorn.jpg");
    var srcImage = Image.FromFile(imageFile);
    using (var streak = new MemoryStream())
    {
      srcImage.Save(streak, ImageFormat.Png);
      return File(streak.ToArray(), "image/png");
    }     
}

Now you can call it in a view like this

<img src="@Url.Action("GetImg","YourControllerName")"  alt="alt text"/>
Shyju
  • 197,032
  • 96
  • 389
  • 477
  • I have the image in a System.Drawing.Image variable in the Controller that I want to display in the view. I would like to avoid having to save to an actual image file in order to display the image if possible. – d456 Jul 18 '12 at 18:57
  • you can simply first 2 lines then. The variable called src is of type Drawing.Image. So use your variable name (which has the Image) instead of srcImage in my answer – Shyju Jul 18 '12 at 18:58
  • 2
    Thanks. Just what I was looking for then. – d456 Jul 18 '12 at 20:16