Display image from database in asp mvc
C#asp.net MvcC# Problem Overview
I'm getting an image in a byte array format from the controller, How can I display this in the view? in the simplest way.
C# Solutions
Solution 1 - C#
Create a controller for displaying images with a Show action that takes the id of the image to display from the database. The action should return a FileResult that contains the image data with the appropriate content type.
public class ImageController : Controller
{
public ActionResult Show( int id )
{
var imageData = ...get bytes from database...
return File( imageData, "image/jpg" );
}
}
In your view, construct the image and use the image id to construct a path for the image using the controller and action.
<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>' />
Solution 2 - C#
The accepted answer of using this:
<img src='<%= Url.Action( "show", "image", new { id = ViewData["imageID"] } ) %>'
is fine, but outdated for mvc 4. The updated syntax should now read:
<img src='@Url.Action( "show", "image", new { id = ViewData["imageID"] })' />
Also, I find that when I need this functionality I'm already passing other data to the view so it's nice to use the Model instead of the ViewData.
public class MyModel {
public string SomeData {get;set;}
public int FileId {get; set;}
}
From your controller:
public ActionResult Index() {
MyEntity entity = fetchEntity();
MyModel model = new MyModel {
SomeData = entity.Data,
FileId = entity.SomeFile.ID
};
return View(model);
}
Finally from your view:
<img src='@Url.Action("show", "image", new { id = Model.FileId })' />
The "Show" method on the controller for the accepted answer will work but I would change the hardcoded "image/jpg" to use File.ContentType - you can store this along with the byte[] so you don't need to guess if users are uploading their own images.
Solution 3 - C#
Every answer here may be correct but the simplest way from my opinion is get byte array or Model containing image and simply add like this
<img src="data:image/jpeg;base64,@(Convert.ToBase64String(Model.Picture))">
Solution 4 - C#
I know this post is rather old but it was one of the first that came up when i was trying to figure out how to do this for the most part Augi answer was correct but most of the assemblies are out dated
-
i download mvc2 preview 1
-
no need to worry about the microsoft.web.mvc stuff i couldnt find any of that stuff anyway and search for about an hour trying to figure out what it evolved into
this is the code i wrote that works for me for displaying an image from a db field of type image
in my controller class which i called store i have this
public ActionResult GetImage(int id)
{
byte[] imageData = storeRepository.ReturnImage(id);
//instead of what augi wrote using the binarystreamresult this was the closest thing i found so i am assuming that this is what it evolved into
return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}
//in my repository class where i have all the methods for accessing data i have this
public byte[] ReturnImage(int id)
{
// i tried his way of selecting the right record and preforming the toArray method in the return statment
// but it kept giving me an error about converting linq.binary to byte[] tried a cast that didnt work so i came up with this
byte[] imageData = GetProduct(id).ProductImage.ToArray();
return imageData;
}
now for my view page i tried al kinds of ways i found in these forms and nothing worked i am assuming they were just outdated so i tried on a whim the simplest of all thing i could think of and it worked perfectly
<image src='/store/getimage/<%= Html.Encode(Model.productID) %>' alt="" />
i kept getting an error from the site about posting img tags so make sure you change the above image to img
hope that helps stop anyone from hunting all day for a current answer
http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30886
Solution 5 - C#
public ActionResult EmployeeImage(int id)
{
byte[] imageData ="Retrieve your Byte[] data from database";
if (imageData!= null && imageData.Length > 0)
{
return new FileStreamResult(new System.IO.MemoryStream(imageData), "image/jpeg");
}
}
Solution 6 - C#
Assuming you have a dataRow (dr) with two columns, "name" and "binary_image" (binary_image contains the binary info)
Byte[] bytes = (Byte[])dr["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dr["Image/JPEG"].ToString();
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();