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:
In the controller:
// 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:
- Uploading a File (Or Files) With ASP.NET MVC – Phil Haack
- 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
- If the image is changing often enough and therefore there is no value in caching
- It gives you a self contained page, limiting the number of http connections