php 图片资源转base64,php将图片文件转成base64编码

/**

* 获取图片的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); //写入文件并保存

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值