Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image from byte array in ASP.NET MVC Core

I have a byte[] stored in a VARBINARY(MAX) column in a table in my database. I want to show this image on my index.cshtml page - but I'm stuck.

My CSHTML looks like this:

@using Microsoft.AspNetCore.Hosting.Internal
@{
    ViewData["Title"] = "Title";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>
@if (!Context.User.Identity.IsAuthenticated)
{
    <p>blah blah.</p>

    <p>blah blah</p>
}

@if (Context.User.Identity.IsAuthenticated)
{
    <p>Hi @(Context.User.Identity.Name)<br/></p>


    <p>Where we off to today?</p>
}

I want to add

<img src="...." /> 

obviously I don't know what to do here.

My model has the byte array data:

 public byte[] UserImage { get; set; }

My controller assigned that the value:

  var model = new IndexViewModel
            {
                Username = user.UserName,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                IsEmailConfirmed = user.EmailConfirmed,
                StatusMessage = StatusMessage,
                UserImage = user.UserImage
            };

but I am using .net core in VS2017 and the answers I have found don't seem to work for me. Any help would be really appreciated.

Thanks Johan

like image 958
Johan Grobler Avatar asked Apr 16 '18 20:04

Johan Grobler


1 Answers

You have two options:

  1. Base64 encode the byte[] and use a Data URI:

    <img src="data:image/png;base64,[base64-encoded byte array here]">
    

    However, bear in mind two things. 1) Data URIs are supported in every modern browser, but notoriously do not work in IE 10 and under. That may not be an issue, but if you need to have legacy IE support, this is a non-starter. 2) Since you're Base64-encoding, the size of the "image" will balloon roughly 50%. As such, Data URIs are best used with small and simple images. If you've got large images or simply a lot of images, your HTML document can become a very large download. Since Data URIs are actually embedded in the HTML code, that means the browser cannot actually begin to render the page at all until the entire HTML document has loaded, which then also means that if it's megabytes in size, your users will be waiting a while.

  2. Create an action that pulls the image from the database and returns it as a FileResult. This is the most optimal path. Essentially, you just need an action that accepts some sort of identifier for the image, which can be used to pull it from the database. You then return the byte[] like:

    return File(myByteArray, "image/png");
    

    In your view, you simply make the image source the route to this action:

    <img src="@Url.Action("GetImage", "Foo", new { id = myImageIdentifier }">
    
like image 183
Chris Pratt Avatar answered Sep 19 '22 03:09

Chris Pratt