Search code examples
asp.net-core-mvc-2.0asp.net-core-mvc-2.1

The binary image can't display on view asp.net core 2.x


I upload an image into a table with byte[] format. My problem is, that when I retrieve that on a view, the image won't show up.

Model

{
   public byte[] image {get; set;}
}

Controller

public async Task<IActionResult> Create(Profile profile, IFormFile image)
{
    if (ModelState.IsValid)
    {
        using (var memoryStream = new MemoryStream())
        {
            image.CopyTo(memoryStream);
            profile.image = memoryStream.ToArray();
        }

        _context.Add(image);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(image);
}

View

<img src="@item.image" />

Solution

  • You cannot simply dump a byte array as the source of an HTML image tag. It has to be a URI. That typically means that you need an action that retrieves the image data from the database and returns it as file:

    [HttpGet("profileimage")]
    public async Task<IActionResult> GetProfileImage(int profileId)
    {
        var profile = _context.Profiles.FindAsync(profileId);
        if (profile?.image == null) return NotFound();
    
        return File(profile.image, "image/jpeg");
    }
    

    Then, you can do something like:

     <img src="@Url.Action("GetProfileImage", new { profileId = item.Id })" />
    

    Alternatively, you can use a Data URI. However, this will result in the entire image data being included in your HTML document, increasing the overall download time of the document and delaying rendering. Additionally, Data URIs must be Base64 encoded, which effectively increases the image size roughly 1.5 times. For small, simple images, it's not too big of a deal, but you definitely should avoid this approach with larger images. Anyways, doing this would look something like:

    <img src="data:image/jpeg;base64,@Convert.ToBase64String(item.image)" />