PHP 保存base64图片

<?php
/**
 * Created by PhpStorm.
 * User: Pasa吴
 * Date: 2019/7/29
 * Time: 15:41
 */

namespace app\common\service;


class Upload
{
    /**
     * 上传图片Base64
     * @param $base64_image_content
     * @return mixed
     */
    public static function saveBase64Image($base64_image_content)
    {
        if(!strstr($base64_image_content, 'data:image/png;base64,')){
            $base64_image_content = 'data:image/png;base64,'.$base64_image_content;
        }
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            //图片后缀
            $type = $result[2];

            //保存位置--图片名
            $image_name = date('His') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . "." . $type;
            $image_url  = '/uploads/image/' . date('Ymd') . '/' . $image_name;
            if (!is_dir(dirname('.' . $image_url))) {
                mkdir(dirname('.' . $image_url),07777,true);
                chmod(dirname('.' . $image_url), 0777);
            }

            //解码
            $decode = base64_decode(str_replace($result[1], '', $base64_image_content));
            if (file_put_contents('.' . $image_url, $decode)) {
                $data['code']      = 0;
                $data['imageName'] = $image_name;
                $data['url']       = $image_url;
                $data['msg']       = '保存成功!';
            } else {
                $data['code']       = 1;
                $data['imgageName'] = '';
                $data['url']        = '';
                $data['msg']        = '图片保存失败!';
            }
        } else {
            $data['code']       = 1;
            $data['imgageName'] = '';
            $data['url']        = '';
            $data['msg']        = 'base64图片格式有误!';
        }
        return $data;
    }
}

调用方法:

//use 或者 require 图片上传服务层
use App\Common\Service\Upload AS UploadService;

    /**
     * 上传base64
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function base64()
    {
        $data = UploadService::saveBase64Image($this->param['thumb']);
        if(!empty($data['url'])){
            $this->res = env('APP_URL').$data['url'];
            return $this->doResponseReturn($this->res, '上传成功');
        }
    }

Pasa吴技术博客
请先登录后发表评论
  • latest comments
  • 总共0条评论