$color = $this->dominant_color($img); //获取图片颜色
$water = $this->make_watermark_img('水印文字', $color); //生成水印图片
$this->add_img_water($file_path, $water['url']); //图片打水印
/**
* 给图片添加水印
* @param string $filename 需添加水印图
* @param string $water 水印图
* @param string $newname 图片新名称
*/
public function add_img_water($filename, $water)
{
list($f_w, $f_h) = getimagesize($filename);
list($w_w, $w_h) = getimagesize($water);
//确定水印起始位置(水印居右下角)
$pos_x = $f_w - $w_w;
$pos_y = $f_h - $w_h;
//创建背景图片的资源
$back_img = imagecreatefromjpeg($filename);
//创建水印图片的资源
$water_img = imagecreatefrompng($water);
//添加水印
imagecopy($back_img, $water_img, $pos_x, $pos_y, 0, 0, $w_w, $w_h);
//保存图片
imagepng($back_img,$filename);
return;
}
/**
* 获取图片主要颜色
* @param $image
* @return array
*/
public function dominant_color($image)
{
$rTotal = $gTotal = $bTotal = $total = 0;
$type = getimagesize($image);//取得图片的大小,类型等
if (isset($type['mime']) && $type['mime'] == 'image/webp') {
$i = imagecreatefromwebp($image);
}else{
$i = imagecreatefromstring(file_get_contents($image));
}
// $i = imagecreatefromjpeg($image);
for ($x = 0; $x < imagesx($i); $x++) {
for ($y = 0; $y < imagesy($i); $y++) {
$rgb = imagecolorat($i, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$rTotal += $r;
$gTotal += $g;
$bTotal += $b;
$total++;
}
}
$rAverage = round($rTotal / $total);
$gAverage = round($gTotal / $total);
$bAverage = round($bTotal / $total);
return array(
'r' => $rAverage,
'g' => $gAverage,
'b' => $bAverage,
);
}
public function make_watermark_img($text, $color)
{
$blue = $color['b'];
$red = $color['r'];
$green = $color['g'];
if (strtoupper(substr(PHP_OS,0,3))==='WIN')
{
$font = "c:/windows/fonts/SIMHEI.TTF";//字体类型,这里为黑体,
}else{
$font = "/usr/share/fonts/simhei.ttf";//字体类型,这里为黑体,
}
$text_len = strlen($text) / 3; //显示的文字
$width = $text_len * 20; //1个字17
$logo = 'uploads/sy.png'; //水印文字图片地址
$size = 14; //字体大小
$img = imagecreate($width,24);//创建一个长为x高为y的空白图片
imagecolorallocate($img,$red,$green,$blue);//设置图片背景颜色,这里背景颜色为#ffffff,也就是白色
// imagecolorallocate($img,0xff,0xff,0xff);//设置图片背景颜色,这里背景颜色为#ffffff,也就是白色
$black=imagecolorallocate($img,100,0x00,0x00);//设置字体颜色,这里为#000000,也就是黑色
imagettftext($img,$size,0,0,16, $black, $font , $text);//将ttf文字写到图片中
$watermark_logo = imagepng($img, $logo);//输出图片,输出png使用imagepng方法,输出gif使用imagegif方法
if (!$watermark_logo) {
return ['status' => false, 'msg' => '生成水印失败'];
}
return ['status' => true, 'url' => $logo];
}