I've a model with a byte array image file that I want to show on the page.
How can I do that without going back to the Database?
All the solutions that I see use an ActionResult to go back to the database to retrieve the image, but I already have the image on the model...
You need to have a byte[] in your DB.
My byte[] is in my Person object:
You need to convert your byte[] in a String. So, I have in my controller :
Next, in my .cshtml file, my Model is a ViewModel. This is what I have in :
I use it like this in my .cshtml file:
"data:image/image file extension;base64,{0}, your image String"
I wish it will help someone !
If you want to present the image, add a method as a helper class or to the model itself and allow the method to convert the byte array image to a image format like PNG or JPG then convert to Base64 string. Once you have that, bind the base64 value on your view in the format
"data:image/[image file type extension];base64,[your base64 string goes here]"
The above is assigned to the
img
tag'ssrc
attribute.The only issue I have with this is the base64 string being too long. So, I would not recommend it for multiple models being shown in a view.
If you can base-64 encode your bytes, you could try using the result as your image source. In your model you might add something like:
And in your view:
If the image isn't that big, and if there's a good chance you'll be re-using the image often, and if you don't have too many of them, and if the images are not secret (meaning it's no big deal if one user could potentially see another person's image)...
Lots of "if"s here, so there's a good chance this is a bad idea:
You can store the image bytes in
Cache
for a short time, and make an image tag pointed toward an action method, which in turn reads from the cache and spits out your image. This will allow the browser to cache the image appropriately.This has the added benefit (or is it a crutch?) of working in older browsers, where the inline images don't work in IE7 (or IE8 if larger than 32kB).
I recommend something along these lines, even if the image lives inside of your model.
I realize you are asking for a direct way to access it right from the view and many others have answered that and told you what is wrong with that approach so this is just another way that will load the image in an async fashion for you and I think is a better approach.
Sample Model:
Sample Method in the Controller:
View
One way is to add this to a new c# class or HtmlExtensions class
then you can do this in any view