php——水印

2 篇文章 0 订阅

很多开发语言都会实现水印功能,之前我用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);
 ?>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值