How to get Image from Controller in MVC and display it as Profile pic in layout.cshtml?


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


Asked by:- jaya
0
: 10940 At:- 2/6/2018 2:01:07 PM
MVC asp.net mvc controller return image from database







2 Answers
profileImage Answered by:- bhanu

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.

1
At:- 2/7/2018 5:12:10 PM


profileImage Answered by:- pika

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")'/>
0
At:- 2/12/2018 6:44:48 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use