Thinkphp 5 Base64 转图片和视频并存储

    $this->saveBase64('data:image/png;base64,'.$base64,'image');
    $this->saveBase64('data:video/mp4;base64,'.$base64,'video');
    /**
     * 
     * 保存在入口目录erweicode
     */
    public function saveBase64($base64_image_content,$type){
        if($type=='video'){ // 视频还原
               $typeInfo = '/^(data:\s*video\/(\w+);base64,)/'; 
        }else{//图片还原
               $typeInfo = '/^(data:\s*image\/(\w+);base64,)/'; 
        }
        if (preg_match($typeInfo, $base64_image_content, $result)){
                  //图片后缀
                  $type = $result[2];
                  //保存位置--图片名
                  $image_name=date('His').str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT).".".$type;
                  $image_file_path = '/erweicode/'.date('Ymd');
                  $image_file = ROOT_PATH.'public'.$image_file_path;
                  $imge_real_url = $image_file.'/'.$image_name;
                  $imge_web_url = $image_file_path.'/'.$image_name;
                  if (!file_exists($image_file)){
                    mkdir($image_file, 0700);
                    fopen($image_file.'\\'.$image_name, "w");
                  } 
                  //解码
                  $decode=base64_decode(str_replace($result[1], '', $base64_image_content));
                  if (file_put_contents($imge_real_url, $decode)){
                        $data['code']=200;
                        $data['imageName']=$image_name;
                        $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ?"https://": "http://";
                        //$wzurl = $protocol . $_SERVER['HTTP_HOST'];
                        $data['url']=$protocol .$_SERVER['HTTP_HOST'].'/public'.$imge_web_url;
                        $data['msg']='保存成功!';
                  }else{
                    $data['code']=-1;
                    $data['imgageName']='';
                    $data['url']='';
                    $data['msg']='图片保存失败!';
                  }
        }else{
            $data['code']=-2;
            $data['imgageName']='';
            $data['url']='';
            $data['msg']='base64图片格式有误!';
        }       
        return $data;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值