<?php
/**
*@param [string] 传过来的参数是文件名字符串
*@return [array] 返回值是一个数组,包含图片宽度、高度、创建和输出的字符串以及扩展名
*/
function getImageInfo($filename){
if(@!$info=getimagesize($filename)){//getimagesize()函数可以得到文件信息,
//还可以判断图片是否为真实的图片类型,详细功能见PHP手册
exit('文件不是真实图片');
}
//print_r($info);可以查手册看一下这个数组中每个参数的含义
$fileInfo['width']=$info[0];
$fileInfo['height']=$info[1];
$mime=image_type_to_mime_type($info[2]);//info[2]这个是图片类型对应的数字,此函数可以根据该数字返回出文件对应的MIME类型,详细见手册
//echo $mime;看一下这个$mime的输出格式,你就会理解下面为什么会这么做了
$createFun=str_replace('/', 'createfrom', $mime);//将$mime中的'/'替换成'createfrom',
//因为后边要用到imagecreatefromjpeg/jpg/png 这个函数,这样就可以动态使用不同的函数了
$outFun=str_replace('/', '', $mime);
$fileInfo['createFun']=$createFun;
$fileInfo['outFun']=$outFun;
$fileInfo['ext']=strtolower(image_type_to_extension($info[2]));//image_type_to_extension()是得到文件后缀名函数
return $fileInfo;//返回文件信息
}
function waterImage($dstName,$srcName,$position=0,$dest='images/waterImage',$pre='waterImage_',$pct=50,$delSource=false){
// $dstName='images/2.jpg';
// $srcName='images/1.png';
// $position=0;//图片水印的位置 0代表左上角
// $pct=50;//大概是表示图片水印的透明度吧
// $dest='images/waterImage';//默认保存的位置
// $pre='waterImage_';//默认文件名前缀
// //获取图片信息
$dstInfo=getImageInfo($dstName);
$srcInfo=getImageInfo($srcName);
//创建画布
$dst_im=$dstInfo['createFun']($dstName);
$src_im=$srcInfo['createFun']($srcName);
$src_width=$srcInfo['width'];
$src_height=$srcInfo['height'];
$dst_width=$dstInfo['width'];
$dst_height=$dstInfo['height'];
switch ($position) {
case 0://左上角位置
$x=0;
$y=0;
break;
case 1://中间位置
$x=($dst_width-$src_width)/2;
$y=0;
break;
case 2://右上角
$x=$dst_width-$src_width;
$y=0;
break;
case 3://左中位置
$x=0;
$y=($dst_height-$src_height)/2;
break;
case 4://正中间位置
$x=($dst_width-$src_width)/2;
$y=($dst_height-$src_height)/2;
break;
case 5://右中位置
$x=$dst_width-$src_width;
$y=($dst_height-$src_height)/2;
break;
case 6://左下角位置
$x=0;
$y=$dst_height-$src_height;
break;
case 7://下中位置
$x=($dst_width-$src_width)/2;
$y=$dst_height-$src_height;
break;
case 8://右下角位置
$x=$dst_width-$src_width;
$y=$dst_height-$src_height;
break;
default:
$x=0;
$y=0;
break;
}
//图片合并(函数用法及参数含义见手册)
imagecopymerge($dst_im, $src_im, $x, $y, 0, 0, $src_width, $src_height, $pct);
if($dest && !file_exists($dest)){
mkdir($dest,0777,true);
}
$randNum=mt_rand(100000,999999);
$dstName="{$pre}{$randNum}".$dstInfo['ext'];
$destination=$dest?$dest.'/'.$dstName:$dstName;
$dstInfo['outFun']($dst_im,$destination);
imagedestroy($src_im);
imagedestroy($dst_im);
if($delSource){
@unlink($filename);
}
return $destination;
}
$filename="images/4.jpg";
$logo="images/1.png";
//waterImage($filename,$logo,4);
waterImage($filename,$logo,8);
?>
网友评论