Home > Article > Backend Development > How to convert images to base64 encoding format in php
php method to convert images to base64 encoding format: first read the image stream; then use the [base64_encode] function to convert the encoding format.
Recommended: "php video tutorial"
PHP save Base64 image base64_decode problem
PHP has very good support for Base64. It has built-in base64_encode and base64_decode which are responsible for Base64 encoding and decoding of images.
In terms of 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 will be added to the encoding data:image/png;base64, which is originally used for base64 recognition. However, if you put it directly into PHP and use the base64_decode function to decode it, the final saved image file format will be damaged. 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); //写入文件并保存
The above is the detailed content of How to convert images to base64 encoding format in php. For more information, please follow other related articles on the PHP Chinese website!