当前位置: 首页 > 科技观察

PHP给图片加文字或图片水印的实现代码

时间:2023-03-13 22:58:07 科技观察

有时候上传图片的时候,需要给图片加水印。水印一般为文字或图片标识水印。让我们看一下这两种添加方法。1、文字水印文字水印是在图片上添加文字,主要使用gd库的imagefttext方法,需要字体文件。效果图如下:$dst_path='dst.jpg';//创建图片示例$dst=imagecreatefromstring(file_get_contents($dst_path));//放文字$font='./simsun.ttc';//字体路径$black=imagecolorallocate($dst,0x00,0x00,0x00);//字体颜色imagefttext($dst,13,0,20,20,$black,$font,'快乐编程');//输出图片列表($dst_w,$dst_h,$dst_type)=getimagesize($dst_path);switch($dst_type){case1://GIFheader('Content-Type:image/gif');imagegif($dst);break;case2://JPGheader('Content-Type:image/jpeg');imagejpeg($dst);break;case3://PNGheader('Content-Type:image/png');imagepng($dst);中断;默认:中断;}imagedestroy($dst);新建一张图片,然后打印文字水印://imagecreatefromstring//imageCreateFromPngCreateanewimagefromfileorURL创建图片对象//Createa300x100image,新建一张图片$im=imagecreatetruecolor(500,300);//setcolor$red=imagecolorallocate($im,0xFF,0x00,0x00);$black=imagecolorallocate($im,0x00,0x00,0x00);//使背景变红//functionimagefilledrectangle($image,$x1,$y1,$x2,$y2,$color){}imagefilledrectangle($im,0,0,300,100,$red);//Pathtoourttffontfile$font_file='./font/Arial.ttf';//imagefttext($image,$size,$angle,$x,$y,$color,$fontfile,$text,$extrainfo=null)//绘制文本'PHPManual'usingfontsize13imagefttext($im,13,0,150,50,$black,$font_file,'PHPManual');//Outputimagetothebrowserheader('Content-Type:image/png');imagepng($im);imagedestroy($im);2.图片水印imageWatermark是将一张图片加到另一张图片上,主要使用gd库的imagecopy和imagecopymerge$dst_path='myimage.jpg';$src_path='http://www.logodashi.com/FileUpLoad/inspiration/636003768803214440.jpg';//创建图片实例$dst=imagecreatefromstring(file_get_contents($dst_path));$src=imagecreatefromstring(file_get_contents($src_path));//获取水印图片列表的宽高($src_w,$src_h)=getimagesize($src_path);//复制水印图片到目标图片,最后一个参数50是设置透明度,这里实现半透明效果imagecopymerge($dst,$src,10,10,0,0,$src_w,$src_h,30);//如果是水印图片本身有透明色,然后使用imagecopy方法//imagecopy($dst,$src,10,10,0,0,$src_w,$src_h);//输出图像列表($dst_w,$dst_h,$dst_type)=getimagesize($dst_path);switch($dst_type){case1://GIFheader('Content-Type:image/gif');imagegif($dst);break;case2://JPGheader('Content-Type:image/jpeg');imagejpeg($dst);break;case3://PNGheader('Content-Type:image/png');imagepng($dst);break;default:break;}imagedestroy($dst);图片销毁($src);效果图:3.其他图像处理相关函数/**返回图像大小和图像类型//getthesizeofanimage$size=getimagesize("http://image18-c.poco.cn/mypoco/myphoto/20160901/20/17857099520160901203311082.jpg?750x956_120");print_r($size);//打印结果Array([0]=>750[1]=>956[2]=>2[3]=>width="750"height="956"[bits]=>8[channels]=>3[mime]=>image/jpeg)*//***imagecopy——复制部分图像*///boolimagecopy(resource$dst_im,resource$src_im,int$dst_x,int$dst_y,int$src_x,int$src_y,int$src_w,int$src_h)//复制src_im图像中坐标从src_x,src_y开始,宽度为src_w,高度为src_h的部分到dst_im坐标为dst_x和dst_y的图像/***http://php.net/manual/zh/function.imagecopymerge.php*imagecopymerge——复制并合并部分图像*boolimagecopymerge(resource$dst_im,resource$src_im,int$dst_x,int$dst_y,int$src_x,int$src_y,int$src_w,int$src_h,int$pct)***/