用php将图片生成base64编码

经常需要用到将上传的图片生成base64编码

如何实现,见以下代码

```

public function getExt($img){
//服务器图片路径
$file = storage_path("app/".$img);
$fi = new \finfo(FILEINFO_MIME_TYPE);
$ext = $fi->file($file);
$ext_list = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif'
];
//科学的取图片的扩展名,即使手工改扩展名也可以正确的取到
$file_ext = $ext_list[$ext];
//base64编码
if($fp = fopen($file,"rb", 0))
{
$gambar = fread($fp,filesize($file));
fclose($fp);
$base64 = base64_encode($gambar);
$image_base64 = "data:image/".$file_ext.";base64,".$base64;
}
return $image_base64."^^".$file_ext;
}

```

    A+
发布日期:2021年02月10日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: