分享PHP实现图片添加水印 压缩 剪切的封装类

分类:PHP_Python| 发布:raodaor| 查看:167 | 发表时间:2015/9/1

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

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

        第一步:打开图片

        第二步:操作图片

        第三步:输出图片

        第四步:销毁图片

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

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

直接上代码:

01<?php
02class Image
03
04  private $info;
05  private $image;
06  public $type;
07  public function __construct($src)
08  {
09    $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代码

001<?php
002//修改图片效果
003$db = mysql_connect('localhost','root','Ctrip07185419') or die('can not connect to database');
004mysql_select_db('moviesite',$db) or die(mysql_error($db));
005//上传文件的路径
006$dir = 'D:\Serious\phpdev\test\images';
007//设置环境变量
008putenv('GDFONTPATH='.'C:\Windows\Fonts');
009$font = "arial";
010//upload_image.php页面传递过来的参数,如果是上传图片
011if($_POST['submit'] == 'Upload')
012{
013  if($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK)
014  {
015    switch($_FILES['uploadfile']['error'])
016    {
017      case UPLOAD_ERR_INI_SIZE:
018        die('The uploaded file exceeds the upload_max_filesize directive');
019      break;
020      case UPLOAD_ERR_FORM_SIZE:
021        die('The upload file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
022      break;
023      case UPLOAD_ERR_PARTIAL:
024        die('The uploaded file was only partially uploaded');
025      break;
026      case UPLOAD_ERR_NO_FILE:
027        die('No file was uploaded');
028      break;
029      case UPLOAD_ERR_NO_TMP_DIR:
030        die('The server is missing a temporary folder');
031      break
032      case UPLOAD_ERR_CANT_WRITE:
033        die('The server fail to write the uploaded file to the disk');
034      break;   
035      case UPLOAD_ERR_EXTENSION:
036        die('The upload stopped by extension');
037      break;       
038    }
039  }
040  $image_caption = $_POST['caption'];
041  $image_username = $_POST['username'];
042  $image_date = date('Y-m-d');
043  list($width,$height,$type,$attr) = getimagesize($_FILES['uploadfile']['tmp_name']);
044  $error = 'The file you upload is not a supported filetype';
045  switch($type)
046  {
047    case IMAGETYPE_GIF:
048      $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error);
049    break;
050    case IMAGETYPE_JPEG:
051      $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error);
052    break;
053    case IMAGETYPE_PNG:
054      $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error);
055    break;
056    default:
057    break;
058  }
059  $query = 'insert into images(image_caption,image_username,image_date) values("'.$image_caption.'" , "'.$image_username.'","'.$image_date.'")';
060  $result = mysql_query($query,$db) or die(mysql_error($db));
061  $last_id = mysql_insert_id();
062  // $imagename = $last_id.'.jpg';
063  // imagejpeg($image,$dir.'/'.$imagename);
064  // imagedestroy($image);
065  $image_id = $last_id;
066  imagejpeg($image , $dir.'/'.$image_id.'.jpg');
067  imagedestroy($image);
068}
069else //如果图片已经上传,则从数据库中取图片名字
070{
071  $query = 'select image_id,image_caption,image_username,image_date from images where image_id='.$_POST['id'];
072  $result = mysql_query($query,$db) or die(mysql_error($db));
073  extract(mysql_fetch_assoc($result));
074  list($width,$height,$type,$attr) = getimagesize($dir.'/'.$image_id.'.jpg');
075}
076//如果是保存图片
077if($_POST['submit'] == 'Save')
078{
079  if(isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir.'/'.$_POST['id'].'.jpg'))
080  {
081    $image = imagecreatefromjpeg($dir.'/'.$_POST['id'].'.jpg');
082  }
083  else
084  {
085    die('invalid image specified');
086  }
087  $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1;
088  switch($effect)
089  {
090    case IMG_FILTER_NEGATE:
091      imagefilter($image , IMG_FILTER_NEGATE);   //将图像中所有颜色反转
092    break;
093    case IMG_FILTER_GRAYSCALE:
094      imagefilter($image , IMG_FILTER_GRAYSCALE); //将图像转换为灰度的
095    break;
096    case IMG_FILTER_EMBOSS:
097      imagefilter($image , IMG_FILTER_EMBOSS);   //使图像浮雕化
098    break;
099    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}
132else
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="" style="float:left;"
143/>-->
144    </body>
145  </html>
146  <?php
147    if($_POST['submit'] == 'Upload')
148    {
149      $imagename = 'images/'.$image_id.'.jpg';
150    }
151    else
152    {
153      $imagename = 'image_effect.php?id='.$image_id.'&e='.$_POST['effect'];
154      if(isset($_POST['emb_caption']))
155      {
156        $imagename .= '&capt='.urlencode($image_caption);
157      }
158      if(isset($_POST['emb_logo']))
159      {
160        $imagename .= '&logo=1';
161      }
162    }
163  ?>
164  <img src="<?php echo $imagename;?>" style="float:left;" alt="" />
165  <table>
166    <tr>
167      <td>Image save as:</td>
168      <td><?php $image_id?></td>
169    </tr>
170    <tr>
171      <td>Height:</td>
172      <td><?php echo $height;?></td>
173    </tr>
174    <tr>
175      <td>Widht:</td>
176      <td><?php echo $width;?></td>
177    </tr>
178    <tr>
179      <td>Upload date:</td>
180      <td><?php echo $image_date;?></td>
181    </tr>
182  </table>
183  <p>You may apply a special effect to your image from the list of option below.  Note:saving an image with any of the filters applied <em>can be undone</em>  </p>
184  <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
185    <div>
186      <input type="hidden" name="id" value="<?php echo $image_id;?>"/>
187      Filter:<select name="effect" id="">
188        <option value="-1">None</option>
189        <?php
190          echo '<option value="'.IMG_FILTER_GRAYSCALE.'" ';
191          if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE)
192          {
193            echo 'selected="selected"';
194          }
195          echo ' >Black and white</option>';
196          echo '<option value="'.IMG_FILTER_GAUSSIAN_BLUR.'"';
197          if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR)
198          {
199            echo ' selected="selected"';
200          }
201          echo '>Blur</option>';
202          echo '<option value="'.IMG_FILTER_EMBOSS.'"';
203          if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS)          {
204            echo 'selected="selected"';
205          }
206          echo '>Emboss</option>';
207          echo '<option value="'.IMG_FILTER_NEGATE.'"';
208          if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE)          {
209            echo 'selected="selected"';
210          }
211          echo '>Negative</option>';
212        ?>
213      </select>
214 
215      <?php
216        echo '<input type="checkbox" name="emb_caption"';
217        if(isset($_POST['emb_caption']))
218        {
219          echo ' checked="checked"';
220        }
221        echo ' />Embed caption in image?';
222        echo '
223';
224        //添加水印选项
225        echo '<input type="checkbox" name="emb_logo" ';
226        if(isset($_POST['emb_logo']))
227        {
228          echo 'checked="checked"';
229        }
230        echo ' />Embed watermarked logo in image?';
231      ?>
232      <input type="submit" value="Preview" name="submit" />
233 
234 
235      <input type="submit" value="Save" name="submit" />
236    </div>
237  </form>
238<?php
239}
240?>

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

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

 

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

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

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

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

1bool 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 透明。

365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/php-python/2113.html