/*
* 生成水印logo
* text 水印文字 bigImgPath 背景图
*/
public static function make_watermark_img($text, $bigImgPath)
{
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 * 17; //1个字17
$logo = 'uploads/'.$text.'.png'; //水印文字图片地址
$size = 12; //字体大小
$img = imagecreate($width,24);//创建一个长为x高为y的空白图片
imagecolorallocate($img,0xff,0xff,0xff);//设置图片背景颜色,这里背景颜色为#ffffff,也就是白色
$black=imagecolorallocate($img,0x00,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' => '生成水印失败'];
}
//图片旋转
self::flip($logo, $logo, 45);
//添加水印
$a = self::add_watermark($logo, $bigImgPath);
print_r($a);die;
}
/*
* 添加水印
*/
public static function add_watermark($logo, $bigImgPath)
{
$im = imagecreatefromstring(file_get_contents($bigImgPath));
//获取水印源
$watermark = imagecreatefromstring(file_get_contents($logo));
//获取图、水印 宽高类型
list($bgWidth, $bgHight, $bgType) = getimagesize($bigImgPath);
list($logoWidth, $logoHight, $logoType) = getimagesize($logo);
//定义平铺数据
$x_length = $bgWidth - 10; //x轴总长度
$y_length = $bgHight - 10; //y轴总长度
//创建透明画布 伪白色
$opacity = 30;
$w = imagesx($watermark);
$h = imagesy($watermark);
$cut = imagecreatetruecolor($w,$h);
$white = imagecolorallocatealpha($cut, 255,255,255,0);
imagefill( $cut, 0, 0, $white );
//整合水印
imagecopy($cut, $watermark, 0, 0, 0, 0, $w, $h);
//循环平铺水印
for ($x = 0; $x < $x_length; $x++)
{
for ($y = 0; $y < $y_length; $y++) {
imagecopymerge($im, $cut, $x, $y, 0, 0, $logoWidth, $logoHight, $opacity);
$y += $logoHight;
}
$x += $logoWidth;
}
header("Content-type:image/png");
// imagejpeg 的第二个参数不传, 默认是显示图片
$keys = array_merge(range(0, 9), range('a', 'z'));
$key = '';
for ($i = 0; $i < 15; $i++) {
$key .= $keys[array_rand($keys)];
}
$fileName = $key.time().'.png';
$file_path = 'uploads/'.$fileName;
$img = imagepng($im);
print_r($img);die;
}
/**
* @param $filename // 图片原始地址
* @param $src // 旋转后图片保存地址
* @param int $degrees // 旋转角度
* @return bool
*/
public static function flip($filename,$src,$degrees = 45)
{
//读取图片
$data = @getimagesize($filename);
if($data==false)return false;
//读取旧图片
switch ($data[2]) {
case 1:
$src_f = imagecreatefromgif($filename);break;
case 2:
$src_f = imagecreatefromjpeg($filename);break;
case 3:
$src_f = imagecreatefrompng($filename);break;
}
if($src_f=="")return false;
$rotate = @imagerotate($src_f, $degrees,0);
if(!imagejpeg($rotate,$src,100))return false;
@imagedestroy($rotate);
return true;
}