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


Posted in PHP onAugust 17, 2015

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

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'],false);
  $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'],false);
  $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 database');
mysql_select_db('moviesite',$db) or die(mysql_error($db));
//上传文件的路径
$dir = 'D:\Serious\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'])
  {
   case UPLOAD_ERR_INI_SIZE:
    die('The uploaded file exceeds the upload_max_filesize directive');
   break;
   case UPLOAD_ERR_FORM_SIZE:
    die('The upload file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
   break;
   case UPLOAD_ERR_PARTIAL:
    die('The uploaded file was only partially uploaded');
   break;
   case UPLOAD_ERR_NO_FILE:
    die('No file was uploaded');
   break;
   case UPLOAD_ERR_NO_TMP_DIR:
    die('The server is missing a temporary folder');
   break; 
   case UPLOAD_ERR_CANT_WRITE:
    die('The server fail to write the uploaded file to the disk');
   break;  
   case UPLOAD_ERR_EXTENSION:
    die('The upload stopped by extension');
   break;    
  }
 }
 $image_caption = $_POST['caption'];
 $image_username = $_POST['username'];
 $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)
 {
  case IMAGETYPE_GIF:
   $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error);
  break;
  case IMAGETYPE_JPEG:
   $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error);
  break;
  case IMAGETYPE_PNG:
   $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error);
  break;
  default:
  break;
 }
 $query = 'insert into images(image_caption,image_username,image_date) values("'.$image_caption.'" , "'.$image_username.'","'.$image_date.'")';
 $result = mysql_query($query,$db) or die(mysql_error($db));
 $last_id = mysql_insert_id();
 // $imagename = $last_id.'.jpg';
 // imagejpeg($image,$dir.'/'.$imagename);
 // imagedestroy($image);
 $image_id = $last_id;
 imagejpeg($image , $dir.'/'.$image_id.'.jpg');
 imagedestroy($image);
}
else //如果图片已经上传,则从数据库中取图片名字
{
 $query = 'select image_id,image_caption,image_username,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(isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir.'/'.$_POST['id'].'.jpg'))
 {
  $image = imagecreatefromjpeg($dir.'/'.$_POST['id'].'.jpg');
 }
 else
 {
  die('invalid image specified');
 }
 $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1;
 switch($effect)
 {
  case IMG_FILTER_NEGATE:
   imagefilter($image , IMG_FILTER_NEGATE);  //将图像中所有颜色反转
  break;
  case IMG_FILTER_GRAYSCALE:
   imagefilter($image , IMG_FILTER_GRAYSCALE); //将图像转换为灰度的
  break;
  case IMG_FILTER_EMBOSS:
   imagefilter($image , IMG_FILTER_EMBOSS);  //使图像浮雕化
  break;
  case IMG_FILTER_GAUSSIAN_BLUR:
   imagefilter($image , IMG_FILTER_GAUSSIAN_BLUR); //用高斯算法模糊图像
  break; 
 }
 if(isset($_POST['emb_caption']))
 {
  imagettftext($image , 12 , 0 , 20 , 20 , 0 , $font , $image_caption);
 }
 if(isset($_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 
}
else
{
?>
 <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 servers:</p>
   <!--<img src="images/<?php echo $imagename;?>" alt="" style="float:left;" />-->
  </body>
 </html>
 <?php
  if($_POST['submit'] == 'Upload')
  {
   $imagename = 'images/'.$image_id.'.jpg';
  }
  else
  {
   $imagename = 'image_effect.php?id='.$image_id.'&e='.$_POST['effect'];
   if(isset($_POST['emb_caption']))
   {
    $imagename .= '&capt='.urlencode($image_caption);
   }
   if(isset($_POST['emb_logo']))
   {
    $imagename .= '&logo=1';
   }
  }
 ?>
 <img src="<?php echo $imagename;?>" style="float:left;" alt="" />
 <table>
  <tr>
   <td>Image save as:</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 $_SERVER['PHP_SELF'];?>" method="post">
  <div>
   <input type="hidden" name="id" value="<?php echo $image_id;?>"/>
   Filter:<select name="effect" id="">
    <option value="-1">None</option>
    <?php 
     echo '<option value="'.IMG_FILTER_GRAYSCALE.'" ';
     if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE)
     {
      echo 'selected="selected"';
     }
     echo ' >Black and white</option>';
     echo '<option value="'.IMG_FILTER_GAUSSIAN_BLUR.'"';
     if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR)
     {
      echo ' selected="selected"';
     }
     echo '>Blur</option>';
     echo '<option value="'.IMG_FILTER_EMBOSS.'"';
     if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS)
     {
      echo 'selected="selected"';
     }
     echo '>Emboss</option>';
     echo '<option value="'.IMG_FILTER_NEGATE.'"';
     if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE)
     {
      echo 'selected="selected"';
     }
     echo '>Negative</option>';
    ?>
   </select><br />
   <?php 
    echo '<input type="checkbox" name="emb_caption"';
    if(isset($_POST['emb_caption']))
    {
     echo ' checked="checked"';
    }
    echo ' />Embed caption in image?';
    echo '<br />';
    //添加水印选项
    echo '<input type="checkbox" name="emb_logo" ';
    if(isset($_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:\Serious\phpdev\test\images';
//设置环境变量
putenv('GDFONTPATH='.'C:\Windows\Fonts');
$font = "arial";
if(isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir.'/'.$_GET['id'].'.jpg'))
{
 $image = imagecreatefromjpeg($dir.'/'.$_GET['id'].'.jpg');
}
else
{
 die('invalid image specified');
}
$effect = (isset($_GET['e'])) ? $_GET['e'] : -1;
switch($effect)
{
 case IMG_FILTER_NEGATE:
  imagefilter($image , IMG_FILTER_NEGATE);
 break;
 case IMG_FILTER_GRAYSCALE:
  imagefilter($image , IMG_FILTER_GRAYSCALE);
 break; 
 case IMG_FILTER_EMBOSS:
  imagefilter($image , IMG_FILTER_EMBOSS);
 break; 
 case IMG_FILTER_GAUSSIAN_BLUR:
  imagefilter($image , IMG_FILTER_GAUSSIAN_BLUR);
 break; 
}
if(isset($_GET['capt']))
{
 //echo $_GET['capt'];
 imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']);
}
if(isset($_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);
?>

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

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

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

PHP 相关文章推荐
一家之言的经验之谈php+mysql扎实个人基本功
Mar 27 PHP
php下删除字符串中HTML标签的函数
Aug 27 PHP
php MYSQL 数据备份类
Jun 19 PHP
php上传文件的增强函数
Jul 21 PHP
PHP迭代器的内部执行过程详解
Nov 12 PHP
PHP获取数组最后一个值的2种方法
Jan 21 PHP
php文件压缩之PHPZip类用法实例
Jun 18 PHP
PHP正则表达式匹配替换与分割功能实例浅析
Feb 04 PHP
php获取linux命令结果的实例
Mar 13 PHP
PHP MVC框架中类的自动加载机制实例分析
Sep 18 PHP
PHP项目多语言配置平台实现过程解析
May 18 PHP
PHP中-&gt;和=&gt;的含义及使用示例解析
Aug 06 PHP
php中switch语句用法详解
Aug 17 #PHP
Linux系统下PHP-FPM的安装和配置教程
Aug 17 #PHP
PHP连接Nginx服务器并解析Nginx日志的方法
Aug 16 #PHP
ThinkPHP开发框架函数详解:C方法
Aug 14 #PHP
提高php编程效率技巧
Aug 13 #PHP
php轻量级的性能分析工具xhprof的安装使用
Aug 12 #PHP
详细解读PHP中接口的应用
Aug 12 #PHP
You might like
PHP 选项及相关信息函数库
2006/12/04 PHP
深入分析使用mysql_fetch_object()以对象的形式返回查询结果
2013/06/05 PHP
PHP5中实现多态的两种方法实例分享
2014/04/21 PHP
php解析http获取的json字符串变量总是空白null
2015/03/02 PHP
php通过正则表达式记取数据来读取xml的方法
2015/03/09 PHP
php阳历转农历优化版
2016/08/08 PHP
JavaScript通过RegExp实现客户端验证处理程序
2013/05/07 Javascript
js二级地域选择的实现方法
2013/06/17 Javascript
JavaScript调用后台的三种方法实例
2013/10/17 Javascript
Java中Timer的用法详解
2015/10/21 Javascript
JS如何判断浏览器类型和详细区分IE各版本浏览器
2017/03/04 Javascript
vue中的非父子间的通讯问题简单的实例代码
2017/07/19 Javascript
详解Vue + Vuex 如何使用 vm.$nextTick
2017/11/20 Javascript
js中split()方法得到的数组长度问题
2018/07/19 Javascript
Nuxt使用Vuex的方法示例
2019/09/06 Javascript
vue prop属性传值与传引用示例
2019/11/13 Javascript
Python2与python3中 for 循环语句基础与实例分析
2017/11/20 Python
linux下python中文乱码解决方案详解
2019/08/28 Python
pytorch sampler对数据进行采样的实现
2019/12/31 Python
pytorch中的自定义数据处理详解
2020/01/06 Python
使用pygame编写Flappy bird小游戏
2020/03/14 Python
详解Python 实现 ZeroMQ 的三种基本工作模式
2020/03/24 Python
python的链表基础知识点
2020/09/13 Python
AmazeUI 缩略图的实现示例
2020/08/18 HTML / CSS
国际知名设计师时装商店:Coggles
2016/09/05 全球购物
英国儿童家具专卖店:GLTC
2016/09/24 全球购物
英国经典球衣网站:Classic Football Shirts
2017/05/20 全球购物
阿里巴巴英国:Alibaba英国
2019/12/11 全球购物
C/C++程序员常见面试题二
2015/11/19 面试题
春风行动实施方案
2014/03/28 职场文书
法院授权委托书范文
2014/08/02 职场文书
先进党组织事迹材料
2014/12/26 职场文书
学校党支部公开承诺书
2015/04/30 职场文书
高中家长意见怎么写
2015/06/03 职场文书
文案策划岗位个人自我评价(范文)
2019/08/08 职场文书
小程序实现侧滑删除功能
2022/06/25 Javascript