0

I am new to ASP.NET MVC so please don't judge me... I am having a problem where the image from my SQL Server (byte data type) is not showing to my view. It says "Cannot convert the byte[] to string". What should I do?

This is my controller method ViewProduct:

public ActionResult ViewProduct()
{         
    return View();
}

public ActionResult ViewProd()
{
    inventoryDBEntities1 dbe = new inventoryDBEntities1();
    return View(dbe.tbl_product.ToList());
}

This is my model class named tbl_product:

public partial class tbl_product
{
    public int productID { get; set; }
    public byte[] prod_image { get; set; }      
}

And this is my view:

@model IEnumerable<PointofSale.Models.tbl_product>

<table>
    <tr>
        <td>
            Image
        </td>
    </tr>

    <tr>
        @foreach (var item in @Model)
        {
            <td>
                // The error is around here ( V )!!
                <img src="@Url.Content(item.prod_image)" height="100" width="100"/>
            </td>
        }
    </tr>
</table>
1
  • @Url.Content expects a string that represents a file path in your application's virtual directory, e.g.: "~/images/exampleImage.png" One might be curious as to why you'd store something like that in a byte[] property. Is it possible that prod_image doesn't hold a file path but instead holds the raw bytes of a binary image? Commented Nov 14, 2021 at 1:53

1 Answer 1

1

You need to display the image with byte[] by converting it as base64 string.

@foreach (var item in @Model)
{
   <td>
       @{
           string imageBase64Data = Convert.ToBase64String(item.prod_image);
           string imageDataURL = string.Format("data:image/png;base64,{0}", imageBase64Data);

           <img src="@Url.Content(imageDataURL)" height="100" width="100" />
        }
   </td>
}

References

Display Image From Byte Array In ASP.NET MVC

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer. It does mean that all images stored in the database would need to be a consistent format, in this case PNGs when they were serialized into the DB. If they could be other formats the data structure would need to record the format along with the bytes to be output into the URL or fed to a converter to produce the PNG base64 string.
Thanks and good point out by Steve. Either post owner to standardize the images' format or with DB table with a column store the file extension. And retrieve it from DB, set the imageDataUrl as String.Format("data:image/png;{0},{1}", file_extension, imageBase64Data);.

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.