Encoding an image and inserting it directly into the code makes it easier for us to optimize web pages and make them faster. This gives us the advantage of speeding up loading by reducing the necessary requests, and also avoids the use of external files.
Base 64 is a type of encoding designed to allow binary data to bypass non-8-bit transport layers. The information encoded with this system will result in a sequence of letters, which constitutes a file and can be decoded and displayed correctly by any web browser.
Encoding the image in base 64
Encoding a file is simple, since PHP includes a library that allows base64 conversion in the following way using the base64_encode.
string base64_encode (string or data)
For example, to encode a text string use the following code:
In the following example we can see how it is encoded/decoded in base64 with PHP:
" //Hello world is displayed
echo $encoded; //SG9sYSBtdW5kbw== is displayed
?>
Once we have seen how a text string is encoded/decoded, we will see this example of how to encode an image in base 64 with PHP:
What we have done is obtain the content of the image from the directory using file_get_contents and convert it to base64 with base64_encode.
To insert it on our website it would be something like this:
echo "
";
