Most modern desktop browsers such as Chrome, Mozilla, Internet Explorer supports images encoded as data url. But there are problems displaying data URLs in some mobile browsers like Android Stock Browser.
Here we are presenting that how we can embed base64 encoded images in various platforms. This is similar to how you embed an image in a HTML email message.
Embed base64 encoded images
Syntax:
1 | <img src=”data:<MIMETYPE>;base64,<BASE64_ENCODED_IMAGE>”> |
Example in HTML:
1 | <img src="”data:image/png;base64,TBORw1KGgoDDAANS…" alt="" /> |
Example in CSS-Background image:
1 2 3 4 5 6 7 | <style type="text/css" > div.my-image { width:150px; height:150px; background-image: url("data:image/jpeg;base64,/9j/5TTQSkZJRgQBAQSSSQABA......"); } </style> |
Example in PHP-convert image to Base64 string:
1 2 3 4 5 6 | function image_to_base64($path_to_image) { $type = pathinfo($path_to_image, PATHINFO_EXTENSION); $image = file_get_contents($path_to_image); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($image); } |
Example in C#-convert image to Base64 string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public string CreateBase64Image(byte[] fileBytes) { Image streamImage; using (MemoryStream ms = new MemoryStream(fileBytes)) { /* Create a new image, saved as a scaled version of the original */ streamImage = ScaleImage(Image.FromStream(ms)); } using (MemoryStream ms = new MemoryStream()) { /* Convert this image back to a base64 string */ streamImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png); return Convert.ToBase64String(ms.ToArray()); } } |
With this technique we can prevent multiple HTTP requests, reducing the loading time of a web page.
Note:
The image is base64 encoded, so it is much larger than it’s binary sibling. This makes the use of this rather limited.