// 给图片加水印
public function addWatermarkFromUrl() {
$rvData=array("success"=>false,"data"=>[],"message"=>"","code"=>200);
$url = input('post.pic_path');
$row_1 = input('post.row_1');
$row_2 = input('post.row_2');
$row_3 = input('post.row_3');
$row_4 = input('post.row_4');
// 临时保存图片的路径
$tempDir = './temp/';
// 生成唯一文件名
$filename = uniqid() . '.jpg';
// 完整保存路径
$savePath = $tempDir . $filename;
// 确保临时目录存在
if (!is_dir($tempDir)) {
mkdir($tempDir, 0777, true);
}
// 从URL下载图片
$imageData = file_get_contents($url);
if ($imageData === false) {
$rvData["code"]=201;
$rvData["message"]="无法从URL下载图片";
return json($rvData);
}
// 保存图片到临时目录
file_put_contents($savePath, $imageData);
// 生成水印图片
$this->addWatermarkToImage($savePath, 20, 30, '#000000',$row_1,$row_2,$row_3,$row_4);
// 返回带有水印的图片路径
$rvData['data'] = "https://".$_SERVER['SERVER_NAME']."/temp/".$filename;
$rvData['success'] = true;
return json($rvData);
}
// 使用GD库给图片添加水印
protected function addWatermarkToImage($imagePath, $x, $y, $color,$row_1,$row_2,$row_3,$row_4) {
// 创建图片资源
$image = imagecreatefromjpeg($imagePath);
if (!$image) {
return false;
}
// 获取图片尺寸
$width = imagesx($image);
$height = imagesy($image);
// 设置水印文字的颜色
list($r, $g, $b) = sscanf($color, "#%02x%02x%02x");
$color = imagecolorallocate($image, $r, $g, $b);
// 字体
$fontType = '/temp/simsun.ttc';
// 根据图片尺寸动态计算字体大小
$baseFontSize = 20;
$scaleFactor = min($width, $height) / 1000; // 假设以1000像素为基准尺寸
$fontsize = intval(max(round($baseFontSize * $scaleFactor), 12)); // 确保字体大小不会小于12
// $fontwidth = imagefontwidth($fontsize) * strlen($row_1);
$fontheight = imagefontheight($fontsize);
$x = 30;
$y = $height - $fontheight - 30;
// 添加水印文字 // imagettftext() 的参数依次是:图片资源, 字体大小, 旋转角度, X坐标, Y坐标, 颜色, 字体文件, 文本内容
imagettftext($image, $fontsize, 0, $x, $y - ($fontheight * 12), $color, $fontType, $row_1);
imagettftext($image, $fontsize, 0, $x, $y - ($fontheight * 8), $color, $fontType, $row_2);
imagettftext($image, $fontsize, 0, $x, $y - ($fontheight * 4), $color, $fontType, $row_3);
imagettftext($image, $fontsize, 0, $x, $y, $color, $fontType, $row_4);
// 保存带有水印的图片
imagejpeg($image, $imagePath, 90);
// 释放图片资源
imagedestroy($image);
return true;
}
thinkphp使用使用GD库给图片添加水印
于 2024-03-20 15:23:57 首次发布