Home  >  Article  >  Backend Development  >  How to convert images to base64 in php?

How to convert images to base64 in php?

青灯夜游
青灯夜游Original
2020-11-05 10:52:493635browse

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)".

How to convert images to base64 in php?

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

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