PHP将base64编码字符串转换成图片并保存到本地

小天天天天    PHP    999+ 次    2022-12-08 22:02:12


我们在开发过程中,很多通过APP或者web前端会通过接口给我们以base64编码字符串的方式上传图片,这个时候我们就需要将这些base64编码字符串转化成图片,并且保存到本地,我们来讲解一下。

//调用方法:

public function uploads(){
    $content = $this->getContent();
    $this->base64_image_content($content,'./uploads');
}

base64编码字符串转换成图片并保存到本地:

public function base64_image_content($base64_image_content,$path){
    if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content,$result)){
        $type = $result[2];
        $new_file = $path."/images/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹,如果没有就创建,并给予最高权限
            mkdir($new_file, 0700);
        }
        $new_file = $new_file.time().rand(1000,9999).".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return '/'.$new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

如果你觉得本篇文章对您有帮助,请打赏作者

上一篇: Composer 国内全量镜像大全

下一篇: PHP将byte格式化为KB、MB、GB等的方法

最新评论

暂无评论

热门文章

最新评论

网站数据

网站文章数:481

今日UV/PV/IP:11/13/11

昨日UV/PV/IP:11/14 /10

TOP