php method to convert images to base64: First create a PHP sample file; then use the "function base64EncodeImage ($image_file) {...}" method to convert the image to base64.
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
Use PHP to convert the image into base64 encoding Implementation method
I believe everyone knows that Base64 is one of the most common encoding methods for transmitting 8Bit byte codes on the Internet. If you are not sure about this, you can check RFC2045~RFC2049, which are Detailed specification of MIME. In this article, we share a PHP method to convert images into base64 encoding format. Friends in need can refer to it.
Let’s first talk about why we need to base64 encode images
base64 is one of the most common encoding methods for transmitting 8Bit byte codes 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 the image and output it
<?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 converted by 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 Script House.
Recommended: "php video tutorial"
The above is the detailed content of How to convert images to base64 in php. For more information, please follow other related articles on the PHP Chinese website!