I am building a website using ASP.NET MVC4 to upload/display images and found a few ways of how to display images, chiefly the below -
1) Store the image as a file locally on the server and use a relative path to display it on the page.
//ImageFile is a property which holds a path to the image in the model
<img src="@item.ImageFile" />
When the page is rendered, this becomes a path like - <img src="/Content/Images/Jellyfish.jpg" />
2) Store the image as a byte array and retrive it using a controller action -
//Use a controller action (GetImg) to get the URL of the image
<img src="@Url.Action("GetImg", "ViewPhotos", new { id = item.ID })" alt="Image" />
When the page is rendered, this becomes a path like - <img src="/ViewPhotos/GetImg/4" alt="Image" />
3) Store the image as a byte array and retrive it in the view directly -
//Directly re-construct the image in the view from the byte array (Image property of the model)
<img src="@String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(item.Image))" />
When the page is rendered, this becomes a path like - <img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAgEA....<long string> .../>
My questions are -
1) What is the difference between 1 and 2 ?
1 directly provides the path to file and 2 provides a URL to it. Are they the same in the background or is one approach better than the other?
I have checked here and it says that - Url.Action will construct the path to the action, returning a url, not the results of executing the action. So when are are results retrieved?
2) Does it makes a performance impact when 3 is used against 1 or 2?
3) Which approach should be used when image sizes are small (less than 1MB) or large ?
Happy if you can point to me any links which can be of help as well. Thanks.
Code -
//Model
public class Photo
{
public int ID { get; set; }
public string ImageFile { get; set; }
public byte[] Image { get; set; }
public string Caption { get; set; }
}
//Controller
public FileContentResult GetImg(int id)
{
byte[] byteArray = db.Photos.Find(id).Image;
if (byteArray != null)
{
return new FileContentResult(byteArray, "image/jpeg");
}
else
{
return null;
}
}
//View (approach 2)
@model IEnumerable<MyPhotoLibrary.Models.Photo>
@foreach (var item in Model) {
<tr>
<td>
<img src="@Url.Action("GetImg", "ViewPhotos", new { id = item.ID })" alt="Image" />
</td>
</tr>
}
//View (this is approach 3)
@model IEnumerable<MyPhotoLibrary.Models.Photo>
@foreach (var item in Model) {
<tr>
<td>
<img src="@String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(item.Image))" />
</td>
</tr>
}