很多开发语言都会实现水印功能,之前我用OC和swift都实现过,最近学下php,顺便练下手,记录下以便查阅。
<?php
//水印
function water($source,$water = '1_jaccty.png',$position = 0,$alpha = 100,$type = "jpeg",$path = 'waterTest',$isRandName = true){
//打开图片
$sourceRes = open($source);
$waterRes = open($water);
//获取原图宽高
$source_info = getimagesize($source);
$source_w = $source_info[0];
$source_h = $source_info[1];
//获取水印的宽高
$water_info = getimagesize($water);
$water_w = $water_info[0];
$water_h = $water_info[1];
//计算位置
$image_slipw = $source_w / 3;
$image_sliph = $source_h / 3;
$position_x = ($position % 3-1)*$image_slipw;
$position_y = floor($position / 3)*$image_sliph;
if ($position!=0) {
$x = mt_rand($position_x,$position_x+$image_slipw-$water_w);
$y = mt_rand($position_y,$position_y+$image_sliph-$water_h);
}else{
$x = mt_rand(0,$source_w-$water_w);
$y = mt_rand(0,$source_h-$water_h);
}
//合并
imagecopymerge($sourceRes, $waterRes, $x, $y, 0, 0, $water_w, $water_h, $alpha);
$imageType = 'image'.$type;//根据$type来调用哪个函数
/*
imagepng();
imagejpeg();
imagewbmp();
*/
//处理path问题
if ($isRandName) {
$name = uniqid().'.'.$type;
}else{
$pathInfo = pathinfo($source);
$name = $pathInfo['filename'].'.'.$type;
}
$path = rtrim($path,'/').'/'.$name;//防止已有/斜线
$imageType($sourceRes,$path);//画图
imagedestroy($sourceRes);
imagedestroy($waterRes);
}
//打开图片的函数
function open($path){
if (!file_exists($path)) {
exit('文件不存在');
}
$info = getimagesize($path);
switch ($info['mime']) {
case 'image/jpeg':
case 'image/jpg':
case 'image/pjpeg':
$res = imagecreatefromjpeg($path);
break;
case 'image/png':
$res = imagecreatefrompng($path);
break;
case 'image/gif':
$res = imagecreatefromgif($path);
break;
case 'image/wbmp':
case 'image/bmp':
$res = imagecreatefromwbmp($path);
break;
}
return $res;
}
$source = "1.jpg";
water($source);
?>