实现步骤:上传文件成功之后,打开文件,进行水印添加,存储覆盖原有文件,实现图片加水印功能
一、安装图像处理库
composer require topthink/think-image
二、使用方法
<?php
declare (strict_types = 1);
namespace app\admin\controller;
use think\exception\ValidateException;
class Upload extends Base
{
public function uploadImgWater(){
if (request()->isPost()){
$namePath = request()->param('type');
$file = request()->file('file');
$upload_dir = '/'.$namePath;
$suffix='jpg,jpeg,png,gif';
$size='3';
try {
validate(['file'=>[
//限制文件大小
'fileSize' => $size * 1024 * 1024,
//限制文件后缀
'fileExt' => 'jpg,jpeg,png,gif'
]],[
'file.fileSize' => '上传的文件大小不能超过'.$size.'M',
'file.fileExt' => '请上传后缀为:'.$suffix.'的文件'
])->check(['file'=>$file]);
$filename = \think\facade\Filesystem::disk('public')->putFile($upload_dir, $file);
if ($filename){
$src = '/uploads/'.str_replace('\\', '/', $filename);
$waterpath = public_path('uploads/').str_replace('\\', '/', $filename);
$image = \think\Image::open($waterpath);
$image->water('./static/index/case/water.png',\think\Image::WATER_NORTHWEST,50)->save(public_path('uploads/').str_replace('\\', '/', $filename));
return json(['code'=>1,'msg'=>'上传成功','data'=>['src'=>$src]]);
}else{
return json(['code'=>0,'msg'=>'上传失败']);
}
}catch (ValidateException $e){
return json(['code'=>0,'msg'=>$e->getMessage()]);
}
}else{
return json(['code'=>0,'msg'=>'非法请求']);
}
}
}
?>