首页 > 作文

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

更新时间:2023-04-06 18:10:06 阅读: 评论:0

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

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

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

第一步:打开图片

第二步:操作图片

第三步:输出图片

第四步:销毁图片

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

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

直接上代码:

<?php class image{  private $info; private $image; public $type; public function __construct($src) {  $this->info=getimagesize($src);  $this->type=image_type_to_extension($this->info['2'],fal);  $fun="imagecreatefrom{$this->type}";  $this->image=$fun($src); } /**  * 文字水印  * @param [type] $font  字体  * @param [type] $content 内容  * @param [type] $size  文字大小  * @param [type] $col  文字颜色(四元数组)  * @param array $location 位置   * @param integer $angle 倾斜角度  * @return [type]     */ public function fontmark($font,$content,$size,$col,$location,$angle=0){  $col=imagecolorallocatealpha($this->image, $col['0'], $col['1'], $col['2'],$col['3']);  imagettftext($this->image, $size, $angle, $location['0'], $location['1'], $col,$font,$content); } /**  * 图片水印  * @param [type] $imagemark 水印图片地址  * @param [type] $dst  水印图片在原图片中的位置  * @param [type] $pct  透明度  * @return [type]     */ public function imagemark($imagemark,$dst,$pct){  $info2=getimagesize($imagemark);  $type=image_type_to_extension($info2['2'],fal);  $func2="imagecreatefrom".$type;  $water=$func2($imagemark);  imagecopymerge($this->image, $water, $dst[0], $dst[1], 0, 0, $info2['0'], $info2['1'], $pct);  imagedestroy($water); } /**  * 压缩图片  * @param [type] $thumbsize 压缩图片大小  * @return [type]   [description]  */ public function thumb($thumbsize){  $imagethumb=imagecreatetruecolor($thumbsize[0], $thumbsize[1]);  imagecopyresampled($imagethumb, $this->image, 0, 0, 0, 0, $thumbsize[0], $thumbsize[1], $this->info['0'], $this->info['1']);  imagedestroy($this->image);  $this->image=$imagethumb; } /** * 裁剪图片  * @param [type] $cutsize 裁剪大小  * @param [type] $location 裁剪位置  * @return [type]   [description]  */  public function cut($cutsize,$location){   $imagecut=imagecreatetruecolor($cutsize[0],$cutsize[1]);   imagecopyresampled($imagecut, $this->image, 0, 0, $location[0], $location[1],$cutsize[0],$cutsize[1],$cutsize[0],$cutsize[1]);   imagedestroy($this->image);   $this->image=$imagecut;  } /**  * 展现图片  * @return [type] [description]  */ public function show(){  header("content-type:".$this->info['mime']);  $funn="image".$this->type;  $funn($this->image); } /**  * 保存图片 * @param [type] $newname 新图片名 * @return [type]   [description] */  public function save($newname){   header("content-type:".$this->info['mime']);   $funn="image".$this->type;   $funn($this->image,$newname.'.'.$this->type);  }  public function __destruct(){   imagedestroy($this->image);  } } ?>

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

给图片添加水印代码:

先看文件check_image_addwatermark.php代码

<?php //修改图片效果$db = mysql_connect('localhost','root','ctrip07185419') or die('can not connect to databa');mysql_lect_db('moviesite',$db) or die(mysql_error($db));//上传文件的路径$dir = 'd:\rious\phpdev\test\images';//设置环境变量putenv('gdfontpath='.'c:\windows\fonts');$font = "arial";//upload_image.php页面传递过来的参数,如果是上传图片if($_post['submit'] == 'upload'){ if($_files['uploadfile']['error'] != upload_err_ok) {  switch($_files['uploadfile']['error'])  {   ca upload_err_ini_size:    die('the uploaded file exceeds the upload_max_filesize directive');   break;   ca upload_err_form_size:    die('the upload file exceeds the max_file_size directive that was specified in the html form');   break;   ca upload_err_partial:    die('the uploaded file was only partially uploaded');   break;   ca upload_err_no_file:    die('no file was uploaded');   break;   ca upload_err_no_tmp_dir:    die('the rver is missing a temporary folder');   break;    ca upload_err_cant_write:    die('the rver fail to write the uploaded file to the disk');   break;     ca upload_err_四级口语考试时间extension:    die('the upload stopped by extension');   break;      } } $image_caption = $_post['caption']; $image_urname = $_post['urname']; $image_date = date('y-m-d'); list($width,$height,$type,$attr) = getimagesize($_files['uploadfile']['tmp_name']); $error = 'the file you upload is not a supported filetype'; switch($type) {  ca imagetype_gif:   $image = imagecreatefromgif($_files['uploadfile']['tmp_name']) or die($error);  break;  ca imagetype_jpeg:   $image = imagecreatefromjpeg($_files['uploadfile']['tmp_name']) or die($error);  break;  ca imagetype_png:   $image = imagecreatefrompng($_files['uploadfile']['tmp_name']) or die($error);  break;  default:  break; } $query = 'inrt into images(image_caption,image_urname,image_date) values("'.$image_caption.'" , "'.$image_urname.'","'.$image_date.'")'; $result = mysql_query($query,$db) or die(mysql_error($db)); $last_id = mysql_inrt_id(); // $imagename = $last_id.'.jpg'; // imagejpeg($image,$dir.'/'.$imagename); // imagedestroy($image); $image_id = $last_id; imagejpeg($image , $dir.'/'.$image_id.'.jpg'); imagedestroy($image);}el //如果图片已经上传,则从数据库中取图片名字{ $query = 'lect image_id,image_caption,image_urname,image_date from images where image_id='.$_post['id']; $result = mysql_query($query,$db) or die(mysql_error($db)); extract(mysql_fetch_assoc($result)); list($width,$height,$type,$attr) = getimagesize($dir.'/'.$image_id.'.jpg');}//如果是保存图片if($_post['submit'] == 'save'){ if(ist($_post['id']) && ctype_digit($_post['id']) && file_exists($dir.'/'.$_post['id'].'.jpg')) {  $image = imagecreatefromjpeg($dir.'/'.$_post['id'].'.jpg'); } el {  die('invalid image specified'); } $effect = (ist($_post['effect'])) ? $_post['effect'] : -1; switch($effect) {  ca img_filter_negate:   imagefilter($image , img_filter_negate);  //将图像中所有颜色反转  break;  ca img_filter_grayscale:   imagefilter($image , img_filter_grayscale); //将图像转换为灰度的  break;  ca img_filter_emboss:   imagefilter($image , img_filter_emboss);  //使图像浮雕化  break;  ca img_filter_gaussian_blur:   imagefilter($image , img_filter_gaussian_blur); //用高斯算法模糊图像  break;  } if(ist($_post['emb_caption'])) {  imagettftext($image , 12 , 0 , 20 , 20 , 0 , $font , $image_caption); } if(ist($_post['emb_logo'])) {  //获取水印图片的尺寸并创建水印  list($wmk_width , $wmk_height) = getimagesize('images/logo.png');  $x = ($width-$wmk_width) / 2;  $y = ($height-$wmk_height)/2;  $wmk = imagecreatefrompng('images/logo.png');  //把水印图片和原图片合并在一起  imagecopymerge($image , $wmk , $x , $y , 0 , 0 , $wmk_width , $wmk_height , 20);  //清除水印图片  imagedestroy($wmk); } imagejpeg($image , $dir.'/'.$_post['id'].'.jpg' , 100); ?> <html>  <head>   <title>here is your pic!</title>  </head>  <body>   <h1>your image has been saved!</h1>   <img src="images/<?php echo $_post['id'];?>.jpg" alt="" />  </body> </html><?php }el{?> <html>  <head>   <title>here is your pic!</title>  </head>  <body>   <h1>so how does it feel to be famous?</h1>   <p>here is the picture you just uploaded to your rvers:</p>   <!--<img src="images/<?php echo $imagename;?>" alt="" style="float:left;" />-->  </body> </html> <?php  if($_post['submit'] == 'upload')  {   $imagename = 'images/'.$image_id.'.jpg';  }  el  {   $imagename = 'image_effect.php?id='.$image_id.'&e='.$_post['effect'];   if(ist($_post['emb_caption']))   {    $imagename .= '&capt='.urlencode($image_caption);   }   if(ist($_post['emb_logo']))   {    $imagename .= '&logo=1';   }  } ?> <img src="<?php echo $imagename;?>" style="float:left;" alt="" /> <table>  <tr>   <td>image save as:&l游戏名字大全男孩t;/td>   <td><?php $image_id?></td>  </tr>  <tr>   <td>height:</td>   <td><?php echo $height;?></td>  </tr>  <tr>   <td>widht:</td>   <td><?php echo $width;?></td>  </tr>  <tr>   <td>upload date:</td>   <td><?php echo $image_date;?></td>  </tr> </table> <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> <form action="<?php echo $_rver['php_lf'];?>" method="post">  <div>   <input type="hidden" name="id" value="<?php echo $image_id;?>"/>   filter:<lect name="effect" id="">    <option value="-1">none</option>    <?php      echo '<option value="'.img_filter_grayscale.'" ';     if四川攻略(ist($_post['effect']) && $_post['effect'] == img_filter_grayscale)     {      echo 'lected="lected"';     }     echo ' >black and white</option>';     echo '<option value="'.img_filter_gaussian_blur.'"';     if(ist($_post['effect']) && $_post['effect'] == img_filter_gaussian_blur)     {      echo ' lected="lected"';     }     echo '>blur</option>';     echo '<option value="'.img_filter_emboss.'"';     if(ist($_post['effect']) && $_post['effect'] == img_filter_emboss)     {      echo 'lected="lected"';     }     echo '>emboss</option>';     echo '<option value="'.img_filter_negate.'"';     if(ist($_post['effect']) && $_post['effect'] == img_filter_negate)     {      echo 'lected="lected"';     }     echo '>negative</option>';    ?>   </lect><br />   <?php     echo '<input type="checkbox" name="emb_caption"';    if(ist($_post['emb_caption']))    {     echo ' checked="checked"';    }    echo ' />embed caption in image?';    echo '<br />';    //添加水印选项    echo '<input type="checkbox" name="emb_logo" ';    if(ist($_post['emb_logo']))    {     echo 'checked="checked"';    }    echo ' />embed watermarked logo in image?';   ?>   <input type="submit" value="preview" name="submit" /><br /><br />   <input type="submit" value="save" name="submit" />  </div> </form><?php }?>

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

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

<?php $dir = 'd:\rious\phpdev\test\images';//设置环境变量putenv('gdfontpath='.'c:\windows\fonts');$font = "arial";if(ist($_get['id']) && ctype_digit($_get['id']) && file_exists($dir.'/'.$_get['id'].'.jpg')){ $image = imagecreatefromjpeg($dir.'/'.$_戈壁沙漠get['id'].'.jpg');}el{ die('invalid image specified');}$effect = (ist($_get['e'])) ? $_get['e'] : -1;switch($effect){ ca img_filter_negate:  imagefilter($image , img_filter_negate); break; ca img_filter_grayscale:  imagefilter($image , img_filter_grayscale); break;  ca img_filter_emboss:  imagefilter($image , img_filter_emboss); break;  ca img_filter_gaussian_blur:  imagefilter($image , img_filter_gaussian_blur); break; }if(ist($_get['capt'])){ //echo $_get['capt']; imagettftext($image, 12, 0, 20, 20, 0, $font, $_get['capt']);}if(ist($_get['logo'])){ list($widht , $height) = getimagesize($dir.'/'.$_get['id'].'.jpg'); list($wmk_width , $wmk_height) = getimagesize('images/logo.png'); $x = ($widht-$wmk_width) / 2; $y = ($height-$wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image , $wmk , $x , $y , 0 , 0 , $wmk_width , $wmk_height , 20); imagedestroy($wmk);}header('content-type:image/jpeg');imagejpeg($image , '' , 100);?>

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

注意主要的逻辑就是通过 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给图片添加水印 压缩 剪切的封装类的全部内容,希望大家对本文介绍感兴趣。

本文发布于:2023-04-06 18:10:01,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/899a371ff7e02b8052b2271a5d8ed5f4.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:PHP添加图片水印、压缩、剪切的封装类.doc

本文 PDF 下载地址:PHP添加图片水印、压缩、剪切的封装类.pdf

标签:水印   图片   图像   函数
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图