Let’s first talk about why we base64 encode images
base64 is one of the most common encoding methods for transmitting 8-bit byte code on the current network. Base64 is not mainly for encryption. Its main purpose is to convert certain binary numbers into ordinary characters for network transmission. Since these binary characters are control characters in the transmission protocol and cannot be transmitted directly, they need to be converted. Although the image may be transmitted directly, we can also turn it into a string and put it directly in the source code, without requiring the browser to download it from the server after reading the source code.
How to use PHP to base64 decode and output images
<?php $img = 'test.jpg'; $base64_img = base64EncodeImage($img); echo '<img src="' . $base64_img . '" />'; function base64EncodeImage ($image_file) { $base64_image = ''; $image_info = getimagesize($image_file); $image_data = fread(fopen($image_file, 'r'), filesize($image_file)); $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data)); return $base64_image; } ?>
Summary
The base64 encoded string obtained after conversion through the above method can be stored in the database when needed It can be read directly from the database to reduce the number of requests when accessing images. This method has been included in MiniFramework's global function library. The above is the entire content of this article. I hope that the content of this article can bring some help to everyone's study or work. Thank you for your support to the PHP Chinese website.
For more related articles on how to use PHP to convert images into base64 encoding, please pay attention to the PHP Chinese website!