PHP添加图片水印、压缩、剪切的封装类

为了防止自己辛苦制作的作品被别人窃取,经常给作品添加水印,以此保证作品的唯一性,那么该怎么给图片添加水印呢,如果作品尺寸过大,该如何处理呢,下面小编给大家详细介绍有关PHP给图片添加水印 压缩 剪切的封装类,需要的朋友可以参考下

给图片添加水印,其实就是把原来的图片和水印添加在一起,下面小编把最近整理的资料分享给大家。

php对图片文件的操作主要是利用GD库扩展。当我们频繁利用php对图片进行操作时,会自然封装很多函数,否则会写太多重复的代码。当有很多对图片的相关函数的时候,我们可以考虑将这些函数也整理一下,因而就有了封装成类的想法。

操作图片主要历经四个步骤:

第一步:打开图片

第二步:操作图片

第三步:输出图片

第四步:销毁图片

1,3,4三个步骤每次都要写,每次又都差不多。真正需要变通的只有操作图片的这一步骤了。操作图片又往往通过1或多个主要的GD函数来完成。

本文封装类里面的四种方法,文字水印(imagettftext()),图片水印(imagecopymerge()),图片压缩,图片剪切(imagecopyresampled()),其余的常用GD函数便不赘述。

直接上代码:

  1. <?php
  2. class Image
  3. {
  4. private $info;
  5. private $image;
  6. public $type;
  7. public function __construct($src)
  8. {
  9. $this->info=getimagesize($src);
  10. $this->type=image_type_to_extension($this->info['2'],false);
  11. $fun="imagecreatefrom{$this->type}";
  12. $this->image=$fun($src);
  13. }
  14. /**
  15. * 文字水印
  16. * @param [type] $font 字体
  17. * @param [type] $content 内容
  18. * @param [type] $size 文字大小
  19. * @param [type] $col 文字颜色(四元数组)
  20. * @param array $location 位置
  21. * @param integer $angle 倾斜角度
  22. * @return [type]
  23. */
  24. public function fontMark($font,$content,$size,$col,$location,$angle=0){
  25. $col=imagecolorallocatealpha($this->image, $col['0'], $col['1'], $col['2'],$col['3']);
  26. imagettftext($this->image, $size, $angle, $location['0'], $location['1'], $col,$font,$content);
  27. }
  28. /**
  29. * 图片水印
  30. * @param [type] $imageMark 水印图片地址
  31. * @param [type] $dst 水印图片在原图片中的位置
  32. * @param [type] $pct 透明度
  33. * @return [type]
  34. */
  35. public function imageMark($imageMark,$dst,$pct){
  36. $info2=getimagesize($imageMark);
  37. $type=image_type_to_extension($info2['2'],false);
  38. $func2="imagecreatefrom".$type;
  39. $water=$func2($imageMark);
  40. imagecopymerge($this->image, $water, $dst[0], $dst[1], 0, 0, $info2['0'], $info2['1'], $pct);
  41. imagedestroy($water);
  42. }
  43. /**
  44. * 压缩图片
  45. * @param [type] $thumbSize 压缩图片大小
  46. * @return [type] [description]
  47. */
  48. public function thumb($thumbSize){
  49. $imageThumb=imagecreatetruecolor($thumbSize[0], $thumbSize[1]);
  50. imagecopyresampled($imageThumb, $this->image, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $this->info['0'], $this->info['1']);
  51. imagedestroy($this->image);
  52. $this->image=$imageThumb;
  53. }
  54. /**
  55. * 裁剪图片
  56. * @param [type] $cutSize 裁剪大小
  57. * @param [type] $location 裁剪位置
  58. * @return [type] [description]
  59. */
  60. public function cut($cutSize,$location){
  61. $imageCut=imagecreatetruecolor($cutSize[0],$cutSize[1]);
  62. imagecopyresampled($imageCut, $this->image, 0, 0, $location[0], $location[1],$cutSize[0],$cutSize[1],$cutSize[0],$cutSize[1]);
  63. imagedestroy($this->image);
  64. $this->image=$imageCut;
  65. }
  66. /**
  67. * 展现图片
  68. * @return [type] [description]
  69. */
  70. public function show(){
  71. header("content-type:".$this->info['mime']);
  72. $funn="image".$this->type;
  73. $funn($this->image);
  74. }
  75. /**
  76. * 保存图片
  77. * @param [type] $newname 新图片名
  78. * @return [type] [description]
  79. */
  80. public function save($newname){
  81. header("content-type:".$this->info['mime']);
  82. $funn="image".$this->type;
  83. $funn($this->image,$newname.'.'.$this->type);
  84. }
  85. public function __destruct(){
  86. imagedestroy($this->image);
  87. }
  88. }
  89. ?>

如果还需要其他操作,只需要再往这个类里面添加就好啦~~

给图片添加水印代码:

先看文件check_image_addwatermark.php代码

  1. <?php
  2. //修改图片效果
  3. $db = mysql_connect('localhost','root','Ctrip07185419') or die('can not connect to database');
  4. mysql_select_db('moviesite',$db) or die(mysql_error($db));
  5. //上传文件的路径
  6. $dir = 'D:\Serious\phpdev\test\images';
  7. //设置环境变量
  8. putenv('GDFONTPATH='.'C:\Windows\Fonts');
  9. $font = "arial";
  10. //upload_image.php页面传递过来的参数,如果是上传图片
  11. if($_POST['submit'] == 'Upload')
  12. {
  13. if($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK)
  14. {
  15. switch($_FILES['uploadfile']['error'])
  16. {
  17. case UPLOAD_ERR_INI_SIZE:
  18. die('The uploaded file exceeds the upload_max_filesize directive');
  19. break;
  20. case UPLOAD_ERR_FORM_SIZE:
  21. die('The upload file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
  22. break;
  23. case UPLOAD_ERR_PARTIAL:
  24. die('The uploaded file was only partially uploaded');
  25. break;
  26. case UPLOAD_ERR_NO_FILE:
  27. die('No file was uploaded');
  28. break;
  29. case UPLOAD_ERR_NO_TMP_DIR:
  30. die('The server is missing a temporary folder');
  31. break;
  32. case UPLOAD_ERR_CANT_WRITE:
  33. die('The server fail to write the uploaded file to the disk');
  34. break;
  35. case UPLOAD_ERR_EXTENSION:
  36. die('The upload stopped by extension');
  37. break;
  38. }
  39. }
  40. $image_caption = $_POST['caption'];
  41. $image_username = $_POST['username'];
  42. $image_date = date('Y-m-d');
  43. list($width,$height,$type,$attr) = getimagesize($_FILES['uploadfile']['tmp_name']);
  44. $error = 'The file you upload is not a supported filetype';
  45. switch($type)
  46. {
  47. case IMAGETYPE_GIF:
  48. $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error);
  49. break;
  50. case IMAGETYPE_JPEG:
  51. $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error);
  52. break;
  53. case IMAGETYPE_PNG:
  54. $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error);
  55. break;
  56. default:
  57. break;
  58. }
  59. $query = 'insert into images(image_caption,image_username,image_date) values("'.$image_caption.'" , "'.$image_username.'","'.$image_date.'")';
  60. $result = mysql_query($query,$db) or die(mysql_error($db));
  61. $last_id = mysql_insert_id();
  62. // $imagename = $last_id.'.jpg';
  63. // imagejpeg($image,$dir.'/'.$imagename);
  64. // imagedestroy($image);
  65. $image_id = $last_id;
  66. imagejpeg($image , $dir.'/'.$image_id.'.jpg');
  67. imagedestroy($image);
  68. }
  69. else //如果图片已经上传,则从数据库中取图片名字
  70. {
  71. $query = 'select image_id,image_caption,image_username,image_date from images where image_id'];
  72. $result = mysql_query($query,$db) or die(mysql_error($db));
  73. extract(mysql_fetch_assoc($result));
  74. list($width,$height,$type,$attr) = getimagesize($dir.'/'.$image_id.'.jpg');
  75. }
  76. //如果是保存图片
  77. if($_POST['submit'] == 'Save')
  78. {
  79. if(isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir.'/'.$_POST['id'].'.jpg'))
  80. {
  81. $image = imagecreatefromjpeg($dir.'/'.$_POST['id'].'.jpg');
  82. }
  83. else
  84. {
  85. die('invalid image specified');
  86. }
  87. $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1;
  88. switch($effect)
  89. {
  90. case IMG_FILTER_NEGATE:
  91. imagefilter($image , IMG_FILTER_NEGATE); //将图像中所有颜色反转
  92. break;
  93. case IMG_FILTER_GRAYSCALE:
  94. imagefilter($image , IMG_FILTER_GRAYSCALE); //将图像转换为灰度的
  95. break;
  96. case IMG_FILTER_EMBOSS:
  97. imagefilter($image , IMG_FILTER_EMBOSS); //使图像浮雕化
  98. break;
  99. case IMG_FILTER_GAUSSIAN_BLUR:
  100. imagefilter($image , IMG_FILTER_GAUSSIAN_BLUR); //用高斯算法模糊图像
  101. break;
  102. }
  103. if(isset($_POST['emb_caption']))
  104. {
  105. imagettftext($image , 12 , 0 , 20 , 20 , 0 , $font , $image_caption);
  106. }
  107. if(isset($_POST['emb_logo']))
  108. {
  109. //获取水印图片的尺寸并创建水印
  110. list($wmk_width , $wmk_height) = getimagesize('images/logo.png');
  111. $x = ($width-$wmk_width) / 2;
  112. $y = ($height-$wmk_height)/2;
  113. $wmk = imagecreatefrompng('images/logo.png');
  114. //把水印图片和原图片合并在一起
  115. imagecopymerge($image , $wmk , $x , $y , 0 , 0 , $wmk_width , $wmk_height , 20);
  116. //清除水印图片
  117. imagedestroy($wmk);
  118. }
  119. imagejpeg($image , $dir.'/'.$_POST['id'].'.jpg' , 100);
  120. ?>
  121. <html>
  122. <head>
  123. <title>Here is your pic!</title>
  124. </head>
  125. <body>
  126. <h1>Your image has been saved!</h1>
  127. <img src="images/<?php echo $_POST['id'];?>.jpg" alt="" />
  128. </body>
  129. </html>
  130. <?php
  131. }
  132. else
  133. {
  134. ?>
  135. <html>
  136. <head>
  137. <title>Here is your pic!</title>
  138. </head>
  139. <body>
  140. <h1>So how does it feel to be famous?</h1>
  141. <p>Here is the picture you just uploaded to your servers:</p>
  142. <!--<img src="images/<?php echo $imagename;?>" alt="" />-->
  143. </body>
  144. </html>
  145. <?php
  146. if($_POST['submit'] == 'Upload')
  147. {
  148. $imagename = 'images/'.$image_id.'.jpg';
  149. }
  150. else
  151. {
  152. $imagename = 'image_effect.php?&e='.$_POST['effect'];
  153. if(isset($_POST['emb_caption']))
  154. {
  155. $imagename .= '&capt='.urlencode($image_caption);
  156. }
  157. if(isset($_POST['emb_logo']))
  158. {
  159. $imagename .= '&logo=1';
  160. }
  161. }
  162. ?>
  163. <img src="<?php echo $imagename;?>" alt="" />
  164. <table>
  165. <tr>
  166. <td>Image save as:</td>
  167. <td><?php $image_id?></td>
  168. </tr>
  169. <tr>
  170. <td>Height:</td>
  171. <td><?php echo $height;?></td>
  172. </tr>
  173. <tr>
  174. <td>Widht:</td>
  175. <td><?php echo $width;?></td>
  176. </tr>
  177. <tr>
  178. <td>Upload date:</td>
  179. <td><?php echo $image_date;?></td>
  180. </tr>
  181. </table>
  182. <p>You may apply a special effect to your image from the list of option below.
  183. Note:saving an image with any of the filters applied <em>can be undone</em>
  184. </p>
  185. <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
  186. <div>
  187. <input type="hidden" name="id" value="<?php echo $image_id;?>"/>
  188. Filter:<select name="effect" >
  189. <option value="-1">None</option>
  190. <?php
  191. echo '<option value="'.IMG_FILTER_GRAYSCALE.'" ';
  192. if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE)
  193. {
  194. echo 'selected="selected"';
  195. }
  196. echo ' >Black and white</option>';
  197. echo '<option value="'.IMG_FILTER_GAUSSIAN_BLUR.'"';
  198. if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR)
  199. {
  200. echo ' selected="selected"';
  201. }
  202. echo '>Blur</option>';
  203. echo '<option value="'.IMG_FILTER_EMBOSS.'"';
  204. if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS)
  205. {
  206. echo 'selected="selected"';
  207. }
  208. echo '>Emboss</option>';
  209. echo '<option value="'.IMG_FILTER_NEGATE.'"';
  210. if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE)
  211. {
  212. echo 'selected="selected"';
  213. }
  214. echo '>Negative</option>';
  215. ?>
  216. </select><br />
  217. <?php
  218. echo '<input type="checkbox" name="emb_caption"';
  219. if(isset($_POST['emb_caption']))
  220. {
  221. echo ' checked="checked"';
  222. }
  223. echo ' />Embed caption in image?';
  224. echo '<br />';
  225. //添加水印选项
  226. echo '<input type="checkbox" name="emb_logo" ';
  227. if(isset($_POST['emb_logo']))
  228. {
  229. echo 'checked="checked"';
  230. }
  231. echo ' />Embed watermarked logo in image?';
  232. ?>
  233. <input type="submit" value="Preview" name="submit" /><br /><br />
  234. <input type="submit" value="Save" name="submit" />
  235. </div>
  236. </form>
  237. <?php
  238. }
  239. ?>

这里面主要是添加水印选项,如果选中添加水印则将logo.png作为水印图片和原来的图片合并在一起。

在预览文件中添加了对应的逻辑,代码如下:

  1. <?php
  2. $dir = 'D:\Serious\phpdev\test\images';
  3. //设置环境变量
  4. putenv('GDFONTPATH='.'C:\Windows\Fonts');
  5. $font = "arial";
  6. if(isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir.'/'.$_GET['id'].'.jpg'))
  7. {
  8. $image = imagecreatefromjpeg($dir.'/'.$_GET['id'].'.jpg');
  9. }
  10. else
  11. {
  12. die('invalid image specified');
  13. }
  14. $effect = (isset($_GET['e'])) ? $_GET['e'] : -1;
  15. switch($effect)
  16. {
  17. case IMG_FILTER_NEGATE:
  18. imagefilter($image , IMG_FILTER_NEGATE);
  19. break;
  20. case IMG_FILTER_GRAYSCALE:
  21. imagefilter($image , IMG_FILTER_GRAYSCALE);
  22. break;
  23. case IMG_FILTER_EMBOSS:
  24. imagefilter($image , IMG_FILTER_EMBOSS);
  25. break;
  26. case IMG_FILTER_GAUSSIAN_BLUR:
  27. imagefilter($image , IMG_FILTER_GAUSSIAN_BLUR);
  28. break;
  29. }
  30. if(isset($_GET['capt']))
  31. {
  32. //echo $_GET['capt'];
  33. imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']);
  34. }
  35. if(isset($_GET['logo']))
  36. {
  37. list($widht , $height) = getimagesize($dir.'/'.$_GET['id'].'.jpg');
  38. list($wmk_width , $wmk_height) = getimagesize('images/logo.png');
  39. $x = ($widht-$wmk_width) / 2;
  40. $y = ($height-$wmk_height) / 2;
  41. $wmk = imagecreatefrompng('images/logo.png');
  42. imagecopymerge($image , $wmk , $x , $y , 0 , 0 , $wmk_width , $wmk_height , 20);
  43. imagedestroy($wmk);
  44. }
  45. header('Content-Type:image/jpeg');
  46. imagejpeg($image , '' , 100);
  47. ?>

最后上传的水印图片效果如下:

注意主要的逻辑就是通过 imagecopymerge() 方法把两个图片合并在一起造成水印效果。来看看这个方法的方法原型和参数:

bool imagecopymerge ( 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 )

将 src_im 图像中坐标从 src_x,src_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。两图像将根据 pct 来决定合并程度,其值范围从 0 到 100。当 pct = 0 时,实际上什么也没做,当为 100 时对于调色板图像本函数和 imagecopy() 完全一样,它对真彩色图像实现了 alpha 透明。

以上内容是本文介绍PHP给图片添加水印 压缩 剪切的封装类的全部内容,希望大家对本文介绍感兴趣。