做水印是爬坑n次,原因还是对GD库不熟。 开始写水印用imagestring(),这个方法功能比较简单且只支持英文。 然后iconv(),这方法并不是默认的函数,要启用的话需要修改php.ini中的extension=php_iconv.dll注释(同时iconv.dll也要copy到指向的目录。 ```php $text = iconv("gb2312","utf-8",'水印'); ``` 似乎我的mb扩展是打开的,所以可以用mb_convert_encoding。 ```php mb_convert_encoding('水印', 'html-entities', 'utf-8'); ``` 哎,好不容易写好了方法,我想可以加上@用户,但是boss说只要公司logo+名字,用ps做成图片就好。 所以又要重写,但是我其实比较倾向用文字,灵活些吧,不过imagettftext()必须要ttf的字体文件有点麻烦。 然后,做好水印,居中放置。 ```php imagecopy($simage,$watermark,$width/2-$width2/2,$height/2-$height2/2,0,0,350,33); ``` 接着对应新需求:大小要求随背景图放大缩小,并且位置改为页面右下角,所以方法改为 imagecopyresized, 同时debug,上传png图片背景变成黑色,需要提前调用imagesaveplpha保存alpha通。 这里同事提醒代码里不能exit,这样用户上传图片,脚本就直接停止运行了。 ```php imagesavealpha($simage, true); imagecopyresized($simage,$watermark,$width-$newheight-$width/5,$height-$newheight-$height/5,0,0,$newheight,$newheight,$width2,$height2); ``` 完整代码如下: ```php //文字水印 function watermark($im){ $path = $im; list($width, $height, $type, $attr) = getimagesize($im); $im = imagecreatefromjpeg($im); $textcolor=imagecolorallocate($im,0,0,0); $textcolor2=imagecolorallocate($im,255,255,255); $tmp = '水印watermark'; $text = mb_convert_encoding($tmp['text'], 'html-entities', 'utf-8'); $font = $tmp['font']; $fontSize = 16; $length = strlen($text); $posX = $width/2-$length*$fontSize/2; $posY = $height - $fontSize*1; imagettftext($im,$fontSize,0,$posX,$posY,$textcolor,$font,$text); imagettftext($im,$fontSize,0,$posX-1,$posY,$textcolor2,$font,$text); imagejpeg($im,$path); imagedestroy($im); } //图片水印 function watermark($im){ $path = $im; list($width, $height, $type, $attr) = getimagesize($im); $watermark_path = $this->code('watermark'); list($width2, $height2) = getimagesize($watermark_path); $watermark = imagecreatefrompng($watermark_path); /*1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM */ switch ($type){ case 1: $simage =imagecreatefromgif($im); //从给定的文件名取得的图像 reak; case 2: $simage =imagecreatefromjpeg($im); break; case 3: $simage =imagecreatefrompng($im); break; case 6: $simage =imagecreatefromwbmp($im); break; default: return false; } $newheight = $height/3; if (file_exists($watermark_path)) { imagesavealpha($simage, true); imagecopyresized($simage,$watermark,$width-$newheight-$width/5,$height-$newheight-$height/5,0,0,$newheight,$newheight,$width2,$height2); switch ($type){ case 1: imagegif($simage,$path); //从给定的文件名取得的图像 break; case 2: imagejpeg($simage,$path); break; case 3: imagepng($simage,$path); break; case 6: imagewbmp($simage,$path); break; default: return false; } imagedestroy($simage); imagedestroy($watermark); } } ```