Image Handling On Client Side With Base64 In PHP


Read {count} times since 2020

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.

Syntax

A string can be encrypted using base64 by base64_encode function in PHP. An Example :

$string=“subinsb.com”;

$encrypted=base64_encode($string);

echo $encrypted; // Prints c3ViaW5zYi5jb20=

An Encrypted string can be decrypted by using base64_decode function in PHP. An Example :

$encrypted=“c3ViaW5zYi5jb20=”;

$decrypted=base64_decode($encrypted);

echo $decrypted; // Prints subinsb.com

Image Handling

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 :

$image=file_get_contents("/path/to/image.png");

$encrypted=base64_encode($image);

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

$decrypted=base64_decode($encrypted);

Then we will set the header content type to make the image renderable by the browser.

header(“Content-type: image/png”);

Or you can enter the decrypted string to a file and make that file an image :

file_put_contents("/path/to/a/new/image.png",$decrypted);

Client Side Handling

We will render the image on the client side by passing the base64 encoded string to a URL. The URL is :

data:image/png;base64,encrypted_string_here

A simple Example would be :

You can wrap it all in to a simple function :

function baseImage($f){

$image=file_get_contents($f);

$encrypted=base64_encode($image);

$url=“data:image/png;base64,”.$encrypted;

echo$url;

}

The usage of the function is :

<img src=""/>

That’s all for today.