/**
* 上传文件
* @ApiMethod (POST)
* @param File $file 文件流
*/
public function upload()
{
Config::set('default_return_type', 'json');
//必须设定cdnurl为空,否则cdnurl函数计算错误
Config::set('upload.cdnurl', '');
$chunkid = $this->request->post("chunkid");
if ($chunkid) {
if (!Config::get('upload.chunking')) {
$this->error(__('Chunk file disabled'));
}
$action = $this->request->post("action");
$chunkindex = $this->request->post("chunkindex/d");
$chunkcount = $this->request->post("chunkcount/d");
$filename = $this->request->post("filename");
$method = $this->request->method(true);
if ($action == 'merge') {
$attachment = null;
//合并分片文件
try {
$upload = new Upload();
$attachment = $upload->merge($chunkid, $chunkcount, $filename);
} catch (UploadException $e) {
$this->error($e->getMessage());
}
$this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
} elseif ($method == 'clean') {
//删除冗余的分片文件
try {
$upload = new Upload();
$upload->clean($chunkid);
} catch (UploadException $e) {
$this->error($e->getMessage());
}
$this->success();
} else {
//上传分片文件
//默认普通上传文件
$file = $this->request->file('file');
try {
$upload = new Upload($file);
$upload->chunk($chunkid, $chunkindex, $chunkcount);
} catch (UploadException $e) {
$this->error($e->getMessage());
}
$this->success();
}
} else {
$attachment = null;
//默认普通上传文件
$file = $this->request->file('file');
try {
$upload = new Upload($file);
$attachment = $upload->upload();
$caurl = '.' . $attachment->url;
// dump($caurl);
// exit;
$this->uploadsy($caurl);
} catch (UploadException $e) {
$this->error($e->getMessage());
} catch (\Exception $e) {
$this->error($e->getMessage());
}
$this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
}
}
public function uploadsy($caurl)
{
header("Content-Type:text/html;charset=utf-8");
header("Content-type:image/png");
$size = 15;
//字体类型,本例为黑体
$font = $_SERVER['DOCUMENT_ROOT']."/lucon.ttf";
// dump($font);exit;
$image = imagecreatefromjpeg($caurl);// 加载已有图像
// 设置文字角度
$angle = 0;
// 设置水印文字
$watermarkText = date('Y-m-d H:i:s', time());
// 计算文字的位置
$width = imagesx($image);
$height = imagesy($image);
$fontSize = 20; // 根据需要调整字体大小
$box = imagettfbbox($fontSize, $angle, $font, $watermarkText);
$textWidth = $box[2] - $box[0];
$textHeight = $box[7] - $box[1];
$x = $width - $textWidth - 40; // 右边距10px
$y = $height - $textHeight - 40; // 下边距10px
// 分配颜色和透明度
$color = imagecolorallocatealpha($image, 255, 255, 255, 50);
$ext = 'jpg';
// 写入水印
imagettftext($image, $fontSize, $angle, $x, $y, $color, $font, $watermarkText);
// 生成文件名
// $filename = 'clock/' . date('YmdHis') . '_' . uniqid() . '.' . $ext;
//
// // 构建保存路径
// $filepath = 'uploads/' . $filename;
ImagePNG($image, $caurl);
imagedestroy($image);
return $caurl;
}
fastadmin图片上传增加时间水印
于 2024-08-12 11:27:11 首次发布