Tuesday, 2 September 2014

Embedding images in a page - MVC style

I recently had a need to write some images stored in a database to a page. This was something rare enough that I thought it was worth documenting as it meant putting together a few different pieces.

Examples here are for MVC4, but could be easily adapted for somehing else.

In the View:
<img alt="Restaurant Image" class="RestaurantPhoto" src="data:image/png;base64,@Model.Photo">

In the controller:
byte[] photoData
// populate photoData here
model.Photo = Convert.ToBase64String(photoData, 0, src.photo.Length)

This works by encoding the image as a base 64 string, which is supported by most modern browsers. You might need to change the data at the start to handle different image types.

Pair this with the following two pages:

  1. Uploading a File (Or Files) With ASP.NET MVC - Phil Haack
  2. Convert HttpPostedFileBase to byte[] - Stack Overflow
and you've got an end to end solution for uploading and displaying files.

Why would you / wouldn't you do this?

Doing this is a bad idea in many cases as it means that the image can't be cached. Overall this would tend to make your page loads slower.

However it might be worth doing if
  1. If the image is changing often enough and therefore there is no value in caching
  2. It gives you a self contained page, limiting the number of http connections

No comments:

Post a Comment