private$image;//重绘图片private$imageinfo;//重绘图片的具体信息(array)private$percent=1;//压缩比例,1为原像素比例//上传接口--接收前端传递过来的图片文件publicfunctionUpload(){$file=request()->file('image');if(!$file)returnreturn_msg('400','没有图片文件');// 要上传图片的本地路径$filePath=$file->getRealPath();// 对图片压缩重绘$this->_openImage($filePath);// 将重绘后的图片流赋值使用ob_start();// Let's start output buffering.$fileName=$file->getInfo('name');$ext=pathinfo($fileName,PATHINFO_EXTENSION);//后缀if($ext=='jpg'||$ext=='jpeg'){imagejpeg($this->image);//This will normally output the image, but because of ob_start(), it won't.}if($ext=='png'){imagepng($this->image);//This will normally output the image, but because of ob_start(), it won't.}$contents=ob_get_contents();//Instead, output above is saved to $contentsob_end_clean();//End the output buffer.imagedestroy($this->image);if(!$contents)returnreturn_msg('400','压缩失败');// 上传文件流到七牛云return$this->QiniuUpload($fileName,$contents);}// 上传图片到七牛privatefunctionQiniuUpload($fileName,$result){$accessKey=config("qiniu")['accessKey'];$secretKey=config("qiniu")['secretKey'];$ext=pathinfo($fileName,PATHINFO_EXTENSION);//后缀$key=md5($fileName.time()).'.'.$ext;// 构建鉴权对象$auth=newAuth($accessKey,$secretKey);// 要上传的空间$bucket=config("qiniu")['bucket'];$token=$auth->uploadToken($bucket);$domain=config("qiniu")['domain'];$uploadMgr=newUploadManager();// echo $key;// 调用 UploadManager 的 putFile 方法进行文件的上传--直接上传图片文件//list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);//图片文件流list($ret,$err)=$uploadMgr->put($token,$key,$result);if($err!==null){returnreturn_msg('400',$err);}returnjson(['code'=>'200','msg'=>'七牛图片路径',"data"=>$key,"domain"=>$domain]);}/**
* 内部:打开图片
*/privatefunction_openImage($src){// list($width, $height, $type, $attr) = getimagesize($this->src);list($width,$height,$type,$attr)=getimagesize($src);$this->imageinfo=array('width'=>$width,'height'=>$height,'type'=>image_type_to_extension($type,false),'attr'=>$attr);$fun="imagecreatefrom".$this->imageinfo['type'];// $this->image = $fun($this->src);$this->image=$fun($src);$this->_thumpImage();}/**
* 内部:操作图片
*/privatefunction_thumpImage(){$new_width=$this->imageinfo['width']*$this->percent;$new_height=$this->imageinfo['height']*$this->percent;$image_thump=imagecreatetruecolor($new_width,$new_height);//绘制图片透明底色imagesavealpha($image_thump,true);$black=imagecolorallocate($image_thump,0,0,0);imagefilledrectangle($image_thump,0,0,150,25,$black);$trans_colour=imagecolorallocatealpha($image_thump,0,0,0,127);imagefill($image_thump,0,0,$trans_colour);//将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度imagecopyresampled($image_thump,$this->image,0,0,0,0,$new_width,$new_height,$this->imageinfo['width'],$this->imageinfo['height']);imagedestroy($this->image);$this->image=$image_thump;}