tp6 保存base64图片

 public function upload()
    {
        $data        = Request::param('link');
        $type        = Request::param('type');
        $image_parts = explode(";base64,", $data);
        $image_type  = explode("image/", $image_parts[0])[1];
        $image_data  = base64_decode($image_parts[1]);
        $uniqueName  = uniqid('front_', true) . '.' . $image_type;

        $relativePath = BASE_PATH . '/upload/';
        $savePath     = $relativePath . $uniqueName;
        //        if (!is_dir($relativePath)) {
        //            mkdir($relativePath, 0777, true);
        //            chmod($relativePath, 0777);
        //        }
        file_put_contents($savePath, $image_data);

        if ($savePath) {

            $source_file = $savePath; // 原始图片路径
            $target_file = BASE_PATH . '/upload/' . $uniqueName;

            $source_image = imagecreatefromjpeg($source_file);
            $target_image = imagescale($source_image, 800, 600); // 指定压缩后的宽度和高度

            imagejpeg($target_image, $target_file, 80); // 将图像保存为 JPEG 格式,质量为80
            imagedestroy($source_image);
            imagedestroy($target_image);


            # 上传文件
            $instance = ALi::setConf($type);
            $instance->getBuilder();
            $result = $instance->uploadOss($uniqueName, $target_file);

            if (isset($result['info']['http_code']) && $result['info']['http_code'] == 200) {
                return success(Status::SUCCESS, '操作成功', [
                    "link" => $result['info']['url']
                ]);
            } else {
                return error(Status::ERROR, '传输异常 请重试!', null);
            }
        } else {
            return error(Status::ERROR, '存储失败!', null);
        }
    }

 

posted @ 2023-11-02 14:51  现世中的素人  阅读(159)  评论(0编辑  收藏  举报