Every website needs images. It make the site attractive and beautiful. But sometimes, images won’t get loaded. The latest Browsers have a feature that generates image on a base64 string. Most of the browser have it. In this post I’m going to describe the way to use base64 in displaying images on a website.
What’s base64 ?
Base64 is a encrypting method which is available in many languages. It can be used for encrypting and decrypting. It is not like other hash functions (MD5, SHA 256, SHA 512). Unlike other hash methods, a base64 encrypted string can be directly decrypted. But other hash functions can only be used for checking a value.
A string can be encrypted using base64 by base64_encode function in PHP. An Example :
echo $encrypted; // Prints c3ViaW5zYi5jb20=
An Encrypted string can be decrypted by using base64_decode function in PHP. An Example :
echo $decrypted; // Prints subinsb.com
Images can also be encrypted and decrypted using base64. You might know that images are made by characters. These characters are rendered as images. By encoding these image characters by base64, we will get a simpler, readable character containing string. When we decode this simpler string, we will get back that image. This is the principle we are going to use.
How to Encrypt an Image ?
For this, we will first get the contents of the image file, then we will encrypt it :
The $encrypted variable contains the encrypted image.
How to Decrypt an Encoded Image String?
Get the base64 encoded string of an image. Then decrypt it normally :
$encrypted=“”;// A base64 encoded image string
Then we will set the header content type to make the image renderable by the browser.
Or you can enter the decrypted string to a file and make that file an image :
Client Side Handling
We will render the image on the client side by passing the base64 encoded string to a URL. The URL is :
A simple Example would be :
That’s all for today.