Home  >  Article  >  Backend Development  >  How to convert files to base64 encoding format in php

How to convert files to base64 encoding format in php

L
LOriginal
2020-06-02 09:25:116724browse

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 &#39;<pre class="brush:php;toolbar:false">&#39; . print_r($img_info, true) . &#39;

'; $fp = fopen($app_img_file, "r"); // 图片是否可读权限 if ($fp) { $filesize = filesize($app_img_file); $content = fread($fp, $filesize); $file_content = chunk_split(base64_encode($content)); // base64编码 switch ($img_info[2]) { //判读图片类型 case 1: $img_type = "gif"; break; case 2: $img_type = "jpg"; break; case 3: $img_type = "png"; break; } $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码 } fclose($fp); } return $img_base64; //返回图片的base64 } //调用使用的方法 $img_dir = dirname(__FILE__) . '/uploads/img/11213223.jpg'; $img_base64 = imgToBase64($img_dir); echo ''; //图片形式展示 echo '
'; echo $img_base64; //输出Base64编码

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(&#39;,&#39;, $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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn