Home > Article > Backend Development > How to convert images to base64 in php?
In PHP, you can use the base64_encode() and chunk_split() functions to base64 encode image files and convert them into base64 format. The syntax format is "chunk_split(base64_encode(fread(file, size)".
Recommended: "PHP Video Tutorial"
PHP has very good support for Base64, with built-in base64_encode and base64_decode Responsible for the Base64 encoding and decoding of images.
For encoding, just read the image stream and then use base64_encode to encode it.
/** * 获取图片的Base64编码(不支持url) * @date 2017-02-20 19:41:22 * * @param $img_file 传入本地图片地址 * * @return string */ function imgToBase64($img_file) { $img_base64 = ''; if (file_exists($img_file)) { $app_img_file = $img_file; // 图片路径 $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等 //echo '<pre class="brush:php;toolbar:false">' . print_r($img_info, true) . '
The decoding is a little more troublesome. The reason is that after encoding the image into a base64 string, these characters data:image/png;base64 will be added to the encoding, which is originally used for base64 identification. However, if it is directly put into PHP and decoded using the base64_decode function, it will result in final saving. The image file format is damaged, and the solution is to remove this string of characters first:
$base64_string= explode(',', $base64_string); //截取data:image/png;base64, 这个逗号后的字符 $data= base64_decode($base64_string[1]); //对截取后的字符使用base64_decode进行解码 file_put_contents($url, $data); //写入文件并保存
For more programming-related knowledge, please visit: Introduction to Programming!!
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!