0

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" />

1 Answer 1

1

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)" />
Sign up to request clarification or add additional context in comments.

3 Comments

How the Image property access without Profile model in your action, getting error
Thanks @Chris Pratt, without GetProfileImage action the Image is displaying through your converted 64, img tag.
How do i get this image outside of foreach loop? i want to store it in variable show on different places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.