Last Updated on 2016-06-01.
[:en]Scenario
You have an SQL datatable which contains a BLOB column to save images direcly in your DB as binary and want to show the images on your website.
Solution
Create your EntityFramework and Controller with the common wizards and methods.
Because you cannot directly give a Byte Array to your browser, you have to edit your .cshtml file to insert the images directly into your HTML code as Base64 strings:
@foreach (var item in Model) { @{ String img64 = Convert.ToBase64String(item.image); String img64Url = string.Format("data:image/"+item.imagetype+";base64,{0}", img64); //imagetype can be e.g. gif, jpeg, png etc. } <img src="@img64Url"/> }
A method which offers the images via Controller would be to add ActionResult methods (and/or parameters) for your images.
In your Controller:
public ActionResult GetImage() { byte[] imageByteData = yourmodel.yourtable...yourImage; return File(imageByteData, "image/png"); } //UPDATE 2016-06-07: //Some Browsers like IE do not seem to accept the ContentType parameter of File() and change it to GIF, which may result in lower image quality! //Better use this code: public ActionResult GetImage() { System.IO.MemoryStream ms = new System.IO.MemoryStream(); yourImage.Save(ms, resultImageType); //or use your Byte[] directly with Memorystream constructor ms.Position = 0; return new FileStreamResult(ms, "image/png"); }
Now the src attribute of the image tag should point to /Home/GetImage.
In your View:
<img src='@Url.Action("GetImage", "Home")'/>
Reference[:]
Greetings,
I have used similar code above but cant get my images to display.
I am assuming my images were saved correctly because it states binary data in the table.
i see while stepping through there is data in my image field.
what can i do to trouble my image not showing. Please advise.
var base64 = Convert.ToBase64String(item.BusLogo);
var imagesrc = string.Format(“data:image/png;base64,{0}”, base64);
If all other things are ok, then there is a problem with your code:
var imagesrc = string.Format(“data:image/png;base64,{0}”, base64);
it should look like this:
var imagesrc = string.Format(“data:image/” + “.png” + “;base64,{0}”, img64);
Note that the “.” is missing in your code.
Gracias, me ayudó mucho, no quise escribir en inglés jajaja.