Reputation: 317
I have an issue with my ASP MVC site. I'm trying to convert byte[]
to image "on the fly" inside cshtml file. Here is the code sample:
<div class="col-md-6 portfolio-item">
<table>
@foreach (var item in new Projek2.Models.DatabaseEntities().Photos)
{
<tr>
<td>
@using (var ms = new MemoryStream(item.Photo1))
{
<img [email protected](ms)/>
}
</td>
<td>
@Html.DisplayFor(modelItem => item.FileName)
</td>
</tr>
}
</table>
</div>
It throws an error (InvalidOperation
as far as I remember) during FromStream()
conversion or shows only little placeholders instead of images (like unloaded image).
Anyone knows the trick to convert byte[]
to valid cshtml image?
Upvotes: 0
Views: 528
Reputation: 247591
Using the following assumptions
item.Photo1
is byte[]item
has a mime property that contains photo's mime type like image/png
or image/jpeg
, etc.. Other wise you can derive mime type from file name assuming that name contains file extension.You can create a Data URI scheme and embed it as the source (src) of the image.
<div class="col-md-6 portfolio-item">
<table>
@foreach (var item in new Projek2.Models.DatabaseEntities().Photos)
{
<tr>
<td>
<img src="@System.String.Format("data:{0};base64,{1}",item.Mime,Convert.ToBase64String(item.Photo1))"/>
</td>
<td>
@Html.DisplayFor(modelItem => item.FileName)
</td>
</tr>
}
</table>
</div>
Do note that from my assumption if the item does not store the image type then you can create a helper method to derive the type from the image file name given it contains the file extension of the image. using a format like image\{file extension}
Upvotes: 1