Home > Article > Backend Development > How to convert files to base64 encoding format in php
How to convert image files to base64 encoding format in php
PHP has very good support for Base64 and has built-in The base64_encode and base64_decode are responsible for the 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 data:image/png;base64 will be added to the encoding, 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); //写入文件并保存
Recommended tutorial: "PHP Tutorial》
The above is the detailed content of How to convert files to base64 encoding format in php. For more information, please follow other related articles on the PHP Chinese website!