ASP.NET MVC image from byte array
One way is to add this to a new c# class or HtmlExtensionsclass
public static class HtmlExtensions
{
public static MvcHtmlString Image(this HtmlHelper html, byte[] image)
{
var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
return new MvcHtmlString("<img src='" + img + "' />");
}
}
then you can do this in any view
@Html.Image(Model.MyImageBytes)
You could define a controller action that will serve the image:
public class ImagesController: Controller
{
public ActionResult Index(int id)
{
byte[] imageData = ... go get your image data from the id
return File(imageData, "image/png"); // Might need to adjust the content type based on your actual image type
}
}
and in your view simply point the src
property of the img
tag to this controller action:
<img src="@Url.Action("Index", "Images", new { id = Model.Id })" />