php wangeditor编辑器,base64图片存储为文件

本文介绍了一种在PHP中处理base64编码图片的方法,通过正则表达式匹配并转换图片,实现图片从字符串到文件的存储过程。文章详细解释了如何使用preg_match_all()函数捕获图片数据,然后调用自定义的images_save()函数将图片存储到服务器指定目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php 字符串图片转为文件存储

   /**
     * 编辑器base64_decode图片匹配
     *
     * @author Eric
     * @param $str
     * @return mixed
     */
    public function nei_rong_img($str)
    {
        preg_match_all('/data:\S+/',$str,$res);
        $url = env('APP_URL').'/';
        $res = $res[0];
        if(count($res) > 0)
        {
            admin_toastr('图片保存中,请稍等', 'info');
            foreach ($res as $k => $v)
            {
                $path = $this->images_save(substr($v,0, strlen($v)-1));
                $str = str_replace(
                    $v,
                    $url.$path.'"',
                    $str);
            }
        }
        return $str;
    }

    /**
     * base64_decode图片存储到目录
     *
     * @author Eric
     * @param $imgBase64
     * @return string
     */
    public function images_save($imgBase64)
    {
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/',$imgBase64,$res)) {
            //获取图片类型
            $type = $res[2];

            //图片保存路径
            $new_file = 'upload/'.date('Y').'/'.date('m').'/'.date('d').'/';

            if (!file_exists($new_file)) {

                mkdir($new_file,0755,true);
            }

            //图片名字
            $new_file = $new_file.time().Str::uuid().'.'.$type;
            file_put_contents($new_file,base64_decode(str_replace($res[1],'', $imgBase64)));
            return $new_file;
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值