thinkphp 使用base64上传图片并自动压缩图片 thinkphp使用base64上传,并自动压缩 > 前端在上传前应该按质量压缩下,这样在效率上快很多,不能全依靠后端压缩。 压缩时如宽度大于800,会等比例缩小为800,如宽度小于800,则不操作。 ```php /** * 上传图片 */ public function uploadImg() { //防止内存溢出 ini_set('memory_limit', '256M'); //忽略图片警告 ini_set('gd.jpeg_ignore_warning', 1); $param = $this->param; $img = $param['imgPath']; $type = $param['type']; if (empty($img) || !in_array($type, array('head_img', 'banner', 'types', 'product', 'ad_matrials', 'news', 'icon', 'activity', 'editor', 'develop', 'honor', 'leader_care', 'office'))) { return $this->err('参数错误!'); } $base64 = str_replace('data:image/jpeg;base64,', '', $img); $base64 = str_replace('=', '', $base64); $img_len = strlen($base64); $file_size = $img_len - ($img_len / 8) * 2; if ($file_size > (1024 * 1024 * 10)) { $file_size = number_format(($file_size / 1024 / 1024), 2) . 'mb'; return $this->err("允许上传的文件最大不超过10M,当前文件" . $file_size . "!"); } //匹配出图片的格式 if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img, $result)) { $t = $result[2]; $path = config('app_file_path') . "/upload/admin/" . $type . "/" . date('Ymd') . "/"; if (!file_exists($path)) { //检查是否有该文件夹,如果没有就创建,并给予最高权限 mkdir($path, 0777, true); } $t = $t == 'jpeg' ? 'jpg' : $t; $new_file = $path . Date('YmdHis') . rand(10, 99) . "." . $t; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img)))) { if ($result !== false) { //生成800宽度的缩略图 $image = Image::open($new_file); $result = $image->thumb(800, 100000, Image::THUMB_SCALING)->save($new_file); $file_path = str_replace(config('app_file_path'), "", $new_file); $backData['url'] = $file_path; return $this->suc($backData, '', config('app_img_root')); } else { return $this->err('服务器繁忙!'); } } else { return $this->err('上传失败!'); } } else { return $this->err('上传失败!'); } } ```