Home > Article > Backend Development > How to convert images to base64 encoding in php
The method for php to convert images to base64 encoding is: [
The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.
Introducing how to convert images Before converting to base64 encoding, let’s briefly talk about what base64 encoding is. Maybe many friends don’t know much about it. Let’s take a look at it together.
base64 is the most common one on the current network One of the encoding methods for transmitting 8Bit byte codes. The main function of base64 is not to encrypt. Its main function is to convert certain binary numbers into ordinary characters for network transmission. Since these binary characters are controlled in the transmission protocol Characters cannot be transmitted directly, so they need to be converted. Although images can be transmitted directly, we can also turn them into strings and put them directly in the source code, without the browser needing to download the source code after reading it from the server.
So how do we use PHP to base64 decode and output images? Let’s take a look at the implementation code:
<?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 encoding obtained after conversion through the above method Strings can be stored in the database, and can be read directly from the database when needed to reduce the number of requests when accessing images. In addition, this method has been included in the global function library of MiniFramework.
Recommended learning: phptraining
The above is the detailed content of How to convert images to base64 encoding in php. For more information, please follow other related articles on the PHP Chinese website!