Hi, I would like to know how can I return Image from MVC controller using C#?
Actually I would like to get image and show it on _layout.cshtml page as profile pic when user is Logged in, something like below code
<img src="@Url.Action("GetImage","Account", new { Area = "" })" />
I have saved URL path in database while the image on server folder project/image/profilepic.jpg
Go to your Account Controller, and create GetImage Method like below
public ActionResult GetImage (int UserId)
{
var dir = Server.MapPath("/Images");
var path = Path.Combine(dir, UserId + ".jpg"); //validate the path for security or use other means to generate the path.
return base.File(path, "image/jpeg");
}
OR You can return File like below
[AcceptVerbs(HttpVerbs.Get)]
public FileResult GetImage(int UserId,string imageName)
{
var path = string.Concat(ConfigData.ImagesDirectory, customerId, "\\ProfilePic", imageName);
return new FileStreamResult(new FileStream(path, FileMode.Open), "image/jpeg");
}
Above method is not tested but should work, and it is better than the first method performance wise.
You can get image from controller in MVC using the following C# code also
public ActionResult GetImage()
{
string path = Server.MapPath("~/images/computer.png");
byte[] imageByteData = System.IO.File.ReadAllBytes(path);
return File(imageByteData, "image/png");
}
In the above code, GetImage() action method reads the image file into a byte array. It then uses File() method of the Controller base class to send the contents to the caller. The first parameter is a byte array that represents the file content and the second parameter indicates the MIME content type. Make sure to change the content type as per your needs.
In your view, you can have HTML like below
<img src='@Url.Action("GetImage", "Home")'/>
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly