当前位置:Gxlcms > PHP教程 > 给现有的图片加文字水印php代码

给现有的图片加文字水印php代码

时间:2021-07-01 10:21:17 帮助过:12人阅读

php类库给现有的图片加文字水印,代码不是很完善,欢迎大家多多指教!代码如下:

  1. /*PHP图片加文字水印类库
  2. QQ:3697578482 伤心的歌
  3. 该类库暂时只支持文字水印,位置为右下角,颜色随机
  4. 调用方法:
  5. 1、在需要加水印的文件顶部引入类库:
  6. include_once 'imageClass.php';
  7. 2、声明新类:
  8. $tpl=new image_fu;
  9. 3、给图片水印提供参数:
  10. $tpl->img(图片路径,水印文字,字体路径,字体大小,字体角度);
  11. 比如:$tpl->img('abc.jpg','这是水印文字','ziti.ttf',30,0)
  12. */
  13. class image_fu{
  14. private $image;
  15. private $img_info;
  16. private $img_width;
  17. private $img_height;
  18. private $img_im;
  19. private $img_text;
  20. private $img_ttf='';
  21. private $img_new;
  22. private $img_text_size;
  23. private $img_jd;
  24. function img($img='',$txt='',$ttf='',$size=12,$jiaodu=0){
  25. if(isset($img)&&file_exists($img)){//检测图片是否存在
  26. $this->image =$img;
  27. $this->img_text=$txt;
  28. $this->img_text_size=$size;
  29. $this->img_jd=$jiaodu;
  30. if(file_exists($ttf)){
  31. $this->img_ttf=$ttf;
  32. }else{
  33. exit('字体文件:'.$ttf.'不存在!');
  34. }
  35. $this->imgyesno();
  36. }else{
  37. exit('图片文件:'.$img.'不存在');
  38. }
  39. }
  40. private function imgyesno(){
  41. $this->img_info =getimagesize($this->image);
  42. $this->img_width =$this->img_info[0];//图片宽
  43. $this->img_height=$this->img_info[1];//图片高
  44. //检测图片类型
  45. switch($this->img_info[2]){
  46. case 1:$this->img_im = imagecreatefromgif($this->image);break;
  47. case 2:$this->img_im = imagecreatefromjpeg($this->image);break;
  48. case 3:$this->img_im = imagecreatefrompng($this->image);break;
  49. default:exit('图片格式不支持水印');
  50. }
  51. $this->img_text();
  52. }
  53. private function img_text(){
  54. imagealphablending($this->img_im,true);
  55. //设定颜色
  56. $color=imagecolorallocate($this->img_im,rand(0,255),rand(0,255),rand(0,255));
  57. $txt_height=$this->img_text_size;
  58. $txt_jiaodu=$this->img_jd;
  59. $ttf_im=imagettfbbox($txt_height,$txt_jiaodu,$this->img_ttf,$this->img_text);
  60. $w = $ttf_im[2] - $ttf_im[6];
  61. $h = $ttf_im[3] - $ttf_im[7];
  62. //$w = $ttf_im[7];
  63. //$h = $ttf_im[8];
  64. unset($ttf_im);
  65. $txt_y =$this->img_height-$h;
  66. $txt_x =$this->img_width-$w;
  67. //$txt_y =0;
  68. //$txt_x =0;
  69. $this->img_new=@imagettftext($this->img_im,$txt_height,$txt_jiaodu,$txt_x,$txt_y,$color,$this->img_ttf,$this->img_text);
  70. @unlink($this->image);//删除图片
  71. switch($this->img_info[2]) {//取得背景图片的格式
  72. case 1:imagegif($this->img_im,$this->image);break;
  73. case 2:imagejpeg($this->img_im,$this->image);break;
  74. case 3:imagepng($this->img_im,$this->image);break;
  75. default: exit('水印图片失败');
  76. }
  77. }
  78. //显示图片
  79. function img_show(){echo 'https://www.gxlcms.com/'.$this->img_text.'';}
  80. //释放内存
  81. private function img_nothing(){
  82. unset($this->img_info);
  83. imagedestroy($this->img_im);
  84. }
  85. }
  86. ?>

php

人气教程排行