/**
* 获取图片的Base64编码(不支持url)
* @date 2020-03-28
* @param $img_file 传入本地图片地址
* @param $type 是否带前缀, 1:带, 0:不带
* @return array 0编码结果 1图片类型
*/
function imgToBase64($img_file, $type=1) {
$img_base64 = '';
if (file_exists($img_file)) {
$app_img_file = $img_file; // 图片路径
$img_info = getimagesize($app_img_file); // 取得图片的大小,类型等
$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;
}
//合成图片的base64编码
if($type){
$img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;
}else{
$img_base64 = $file_content;
}
}
fclose($fp);
}
return array($img_base64, $img_type); //返回图片的base64及图片类型
}
//用法
$result = imgToBase64('/www/html/ken.01h.net/xxx.png');
//解码
$base64_string = explode(',', $result[0]); //截取data:image/png;base64, 这个逗号后的字符
$data = base64_decode($base64_string[1]); //对截取后的字符使用base64_decode进行解码
file_put_contents('/www/html/ken.01h.net/yyy.'.$result[1], $data); //写入文件并保存