Returning An Image From ASP.NET MVC Controller

In this article you will learn how we can return an image from ASP.NET MVC Controller.

Introduction
 
This article will help you to return an Image from ASP.NET MVC Controller. In this article, I will use the base controllers File Method.
 
Let's create one empty MVC project. To create empty MVC project you can follow the below steps:
  1. Open Visual Studio

  2. Select on File, New, then click Project or CTRL + SHIFT + N,



  3. Now one dialog box will open from that dialog box. Select Installed Template, Visual C#, then click Web and select ASP.NET Web Application Project.

  4. Provide the name for project and click OK.



  5. Now one more dialog box will open and from that select Empty Project and check MVC Checkbox and press OK.



    After creating MVC project, open Solution Explorer and add new empty controller. To add new controller, right click on the controller and select Add, then click Controller and create empty controller. I am creating a HomeController.  
My Controller Code looks like the following,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace Returning_Image_From_Controller.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Home/  
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.     }  
  18.  
Now, I am creating one folder where I am putting some images. I am adding folder with name "Images" and also adding some JPEG images.
 
After adding folder in my project I am creating one more action method in my home controller with name "GetImage" and I am writing the following code in GetImage action method. 
  1. public ActionResult GetImage(string id)  
  2. {  
  3.        var dir = Server.MapPath("/Images");  
  4.        var path = Path.Combine(dir, id + ".jpg");  
  5.        return base.File(path, "image/jpeg");  
  6.  
In above code I am using base controllers file method.
 
Now, I am adding one View for my Index action and write the following code in Index.cshtml, 
  1. @{  
  2.     Layout = null;
  3. }  
  4.   
  5. <h2>Great Personalities</h2>  
  6. <ul>  
  7.     <li><a href="~/Home/GetImage/1">APJ Abdul Kalam</a> </li>  
  8.     <li><a href="~/Home/GetImage/2">Bill Gates</a> </li>  
  9.     <li><a href="~/Home/GetImage/3">Mark Zuckerberg</a> </li>  
  10.     <li><a href="~/Home/GetImage/4">Steve Jobs</a></li>  
  11. </ul>  
Let's run the Application and you will get the following output.
 
Output
 

Read more articles on ASP.NET: