Home > Article > Backend Development > How to convert image to base64 encoding format in PHP
The base64_encode() function is a built-in function in PHP that is used to convert any data to base64 encoding. In order to convert an image to base64 encoding, you first need to get the contents of the file, which can be done through PHP's file_get_contents() function. This raw data is then passed to the base64_encode() function for encoding.
Required functions:
base64_encode() function is a built-in function in PHP for encoding data using MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode strings in base64. The base64_encoded data takes up 33% more space than the original data.
file_get_contents() function is also a built-in function in PHP for reading files into strings. This function uses server-supported memory mapping technology, which improves performance and makes it the preferred method for reading file contents.
The input image is as follows:
The PHP code program is as follows:
<?php // 获取图像并转换为字符串 $img = file_get_contents('img/001.jpg'); // 将图像字符串数据编码为base64 $data = base64_encode($img); // 显示输出 echo $data;
Output :
/9j/4RUURXhpZgAASUkqAAgAAAAMAAABAwABAAAAgAIAAAEBAwABAAAAkAEAAAIBAwADAAAAng AAAAYBAwABAAAAAgAAABIBAwABAAAAAQAAABUBAwABAAAAAwAAABoBBQABAAAApAAAABsBBQAB AAAArAAAACgBAwABAAAAAgAAADEBAgAeAAAAtAAAADIBAgAUAAAA0gAAAGmHBAABAAAA6AAAACA ... p2wFEq1LzJPMknzajI0ArU1yGkc+ITj2dJPPrPo+H/0DQ4y9NQ/Zgioyy+XLyk5cvqxxy5+b/9k=
Recommended study: "PHP Tutorial"
This article is an introduction to how to convert images to base64 encoding format in PHP. It is simple and easy to understand. I hope Help those in need!
The above is the detailed content of How to convert image to base64 encoding format in PHP. For more information, please follow other related articles on the PHP Chinese website!