Base64 encoding format for images

Today we are taking about the new base64 encoding format for displaying the image or a collection of images. If you have the images with large size then it will take more time to load on the page, base64 encoding provide you the string which will contain all the image data, and load in minimum time on the page. Actually base64_encode() represent the binary data into into an ASCII string format. As you see google also uses the string format for the images to prevent from the server load. You will use this base64 encoded string in ‘img’ tag something like this:

Use base64 encoded string in IMG tag:

<img src="data:image/jpg;base64,ENCODED_STRING_HERE" />

 

I have used the image type as the data:image/jpg for my jpg file, change the data for the gif and png as well data:image/gif, data:image/png respectively.

If you are familiar with PHP, then it is easy for you to generate the base64 encoding string of an image. You just have to read the image file with the help of ‘fopen()’ and ‘fread()’. After that simply just use the PHP’s function base64_encode() to getting the encoding string.

Here is the use of base64_encode() in PHP:

$image_source = "../images/205312_405553186161655_951921660_n.jpg";
$image = fopen($image_source, 'r');
$image_string = fread($image, filesize($image_source));

$img = base64_encode($image_string);
echo $img . '<br />';
echo '<img src="data:image/jpg;base64,'.$img.'" />';

 

On the above code you will get the both, the base64 encoded string of the image and the image as well. This format will not work in IE8 and below, to make working for IE8 and IE7 you have to use this base64 encoded string into you CSS file.

Use base64 encoded string in CSS:

background-image: url("data:image/jpg;base64,YOUR_STRING_HERE);