Reputation: 7829
I have a List of images in byte array format. I want to show these images on a page. This code works:
List<string> photoData = new List<string>();
foreach (var photoBytes in PhotoByteArrayList)
{
var imageBase64Data = Convert.ToBase64String(photoBytes);
var imageUrl = "data:image/JPEG;base64," + imageBase64Data;
photoData.Add(imageUrl);
}
return View(photos);
I have a view that looks like this:
@model List<string>
@{
ViewBag.Title = "Index";
}
<h2>All Images</h2>
@foreach (var item in @Model)
{
<img src="@item" />
}
This works. However: this solution means that the page's HTML contains giant strings of image data. This causes the whole page to take ages to load. What I would rather do is:
How would I accomplish this?
Upvotes: 1
Views: 4160
Reputation: 218762
You can create an action method which returns you the image. Use the File
method to return the image.
public ActionResult MyImg(int id)
{
byte[] bytes =GetByteArrayOfYourImageFromSomeWhere(id);
return File(bytes, "image/jpg");
}
Assumin GetByteArrayOfYourImageFromSomeWhere()
method accepts a unique Id related to your image and return the byte array version of the image stored in your table.
And in your views, you can can call this action method as the image source
<img src="@Url.Action("MyImg","YourControllerName",new { id=250 })" alt="hi" />
Replace 250
with a valid unique numeric id related to your image.
Upvotes: 1