composer 安装:
composer require topthink/think-image
使用
` public function upload_handle() {
$config = [
‘size’ => 20971520,
‘ext’ => ‘jpg,png,jpeg’
];
$file = $this->request->file('file');
$imagesize = getimagesize($file->getInfo()['tmp_name']);
$upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
$save_path = '/uploads/';
$info = $file->validate($config)->move($upload_path); //保存原图
if ($info) {
$url = str_replace('\\', '/', $save_path . $info->getSaveName());
$image = Image::open(str_replace('\/', '/',ROOT_PATH.'public'.$url));
$date_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads').'/'.date('Ymd');
if(!file_exists($date_path)){
mkdir($date_path,0777,true);
}
$thumb_path = $date_path.'/'.$info->getFilename();
$path_parts = pathinfo($thumb_path);
$path = $path_parts['dirname'].'/'.$path_parts['filename'].'_thumb.'.$path_parts['extension']; //缩略图文件名
$file_path = $result = substr($path,strripos($path,"public")+6);
$water_path = str_replace('\/', '/',ROOT_PATH).'public/static/images/water.png';
//->thumb()等比例缩放
//->water()加水印
$image->thumb(1200, 750)->water($water_path,5)->water($water_path)->save($path); //大缩略图(加两个不同位置的水印)
$path = $path_parts['dirname'].'/'.$path_parts['filename'].'_thumb_m.'.$path_parts['extension']; //缩略图文件名
$file_path = $result = substr($path,strripos($path,"public")+6);
$image->thumb(715, 500)->save($path); //小缩略图
$result = [
'error' => 0,
'url' => $file_path,
'size'=>$imagesize[0].'*'.$imagesize[1],
];
} else {
$result = [
'error' => 1,
'message' => $file->getError()
];
}
return json($result);
}`