常用的php图片处理类(水印、等比缩放、固定高宽)分享


Posted in PHP onJune 19, 2015

常用的php图片处理类(水印、等比缩放、固定高宽)分享

<?php  
//PHP 添加水印 & 比例缩略图 & 固定高度 & 固定宽度 类。 
class Image_process{ 
  public $source; //原图 
  public $source_width;  //原图宽度 
  public $source_height; //原图高度 
  public $source_type_id; 
  public $orign_name; 
  public $orign_dirname; 
    
  //传入原图路径 
  public function __construct($source){ 
    $this->typeList = array(1=>'gif',2=>'jpg',3=>'png'); 
    $ginfo = getimagesize($source); 
    $this->source_width = $ginfo[0]; 
    $this->source_height = $ginfo[1]; 
    $this->source_type_id = $ginfo[2]; 
    $this->orign_url = $source; 
    $this->orign_name = basename($source); 
    $this->orign_dirname = dirname($source); 
  } 
    
  //判断图片的文件的格式,返回PHP可识别的编码 
  public function judgeType($type,$source){ 
    if($type == 1){ 
      return imagecreatefromgif($source); //gif 
    }else if($type == 2){ 
      return imagecreatefromjpeg($source); //jpg 
    }else if($type == 3){ 
      return imagecreatefrompng($source); //png 
    }else{ 
      return false; 
    } 
  } 
    
  //生成水印图片 
  public function waterMakeImage($logo){ 
    $linfo = getimagesize($logo); 
    $logo_width = $linfo[0]; 
    $logo_height = $linfo[1]; 
    $logo_type_id = $linfo[2]; 
    $sourceHandle = $this->judgeType($this->source_type_id,$this->orign_url); 
    $logoHandle = $this->judgeType($logo_type_id,$logo); 
    if(!$sourceHandle || !$logoHandle){ 
      return false; 
    } 
    $x = ($this->source_width - $logo_width)/2; 
    $y = ($this->source_height - $logo_height)/2; 
    imagecopy($sourceHandle,$logoHandle,$x,$y,0,0,$logo_width,$logo_height); 
    $newPic = $this->orign_dirname.'\water_'.time().'.'.$this->typeList[$this->source_type_id]; 
    if($this->saveImage($sourceHandle,$newPic)){ 
      imagedestroy($sourceHandle); 
      imagedestroy($logoHandle); 
    } 
  } 
    
  //固定高度宽度 
  public function fixSizeImage($width,$height){ 
    if($width > $this->source_width) $this->source_width; 
    if($height > $this->source_height) $this->source_height; 
    if($width === false){ 
      $width = floor($this->source_width / ($this->source_height / $height)); 
    } 
    if($height === false){ 
      $height = floor($this->source_height / ($this->source_width / $width)); 
    } 
    $this->tinyImage($width,$height); 
  } 
    
  //等比例缩放图片 
  public function scaleImage($scale){ 
    $width = floor($this->source_width * $scale); 
    $height = floor($this->source_height * $scale); 
    $this->tinyImage($width, $height); 
  } 
    
  //创建缩略图 
  public function tinyImage($width,$height){ 
    $tinyImage = imagecreatetruecolor($width,$height); 
    $handle = $this->judgeType($this->source_type_id,$this->orign_url); 
    if(function_exists('imagecopyresampled')){ 
      imagecopyresampled($tinyImage, $handle, 0, 0, 0, 0, $width, $height, $this->source_width, $this->source_height); 
    }else{ 
      imagecopyresized($tinyImage, $handle, 0, 0, 0, 0, $width, $height, $this->source_width, $this->source_height); 
    } 
    $newPic = $this->orign_dirname.'\thumb_'.time().'_'.$width."_".$height.".".$this->typeList[$this->source_type_id]; 
    if($this->saveImage($tinyImage,$newPic)){ 
      imagedestroy($tinyImage); 
      imagedestroy($handle); 
    } 
  } 
  //保存图片 
  private function saveImage($image,$url){ 
    if(imagejpeg($image,$url)){ 
      return true; 
    } 
  } 
} 
$imgHandle = new Image_process('D:\AppServ\www\test\getimg\14061907445601.jpg'); 
//$imgHandle->waterMakeImage('D:\AppServ\www\test\getimg\shougongke.png');  //生成水印图片 
//$imgHandle->fixSizeImage(200,150); //固定长度图片 
$imgHandle->scaleImage(0.2); //等比例缩放 
?>

示例二:

<?php
/**
 * 
 * 图像处理类
 * @author FC_LAMP
 * @internal功能包含:水印,缩略图
 */
class Img
{
 //图片格式
 private $exts = array ('jpg', 'jpeg', 'gif', 'bmp', 'png' );

 /**
 * 
 * 
 * @throws Exception
 */
 public function __construct()
 {
 if (! function_exists ( 'gd_info' ))
 {
  throw new Exception ( '加载GD库失败!' );
 }
 }

 /**
 * 
 * 裁剪压缩
 * @param $src_img 图片
 * @param $save_img 生成后的图片
 * @param $option 参数选项,包括: $maxwidth 宽 $maxheight 高
 * array('width'=>xx,'height'=>xxx)
 * @internal
 * 我们一般的压缩图片方法,在图片过长或过宽时生成的图片
 * 都会被“压扁”,针对这个应采用先裁剪后按比例压缩的方法
 */
 public function thumb_img($src_img, $save_img = '', $option)
 {

 if (empty ( $option ['width'] ) or empty ( $option ['height'] ))
 {
  return array ('flag' => False, 'msg' => '原图长度与宽度不能小于0' );
 }
 $org_ext = $this->is_img ( $src_img );
 if (! $org_ext ['flag'])
 {
  return $org_ext;
 }

 //如果有保存路径,则确定路径是否正确
 if (! empty ( $save_img ))
 {
  $f = $this->check_dir ( $save_img );
  if (! $f ['flag'])
  {
  return $f;
  }
 }

 //获取出相应的方法
 $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] );

 //获取原大小
 $source = $org_funcs ['create_func'] ( $src_img );
 $src_w = imagesx ( $source );
 $src_h = imagesy ( $source );

 //调整原始图像(保持图片原形状裁剪图像)
 $dst_scale = $option ['height'] / $option ['width']; //目标图像长宽比
 $src_scale = $src_h / $src_w; // 原图长宽比
 if ($src_scale >= $dst_scale)
 { // 过高
  $w = intval ( $src_w );
  $h = intval ( $dst_scale * $w );

  $x = 0;
  $y = ($src_h - $h) / 3;
 } else
 { // 过宽
  $h = intval ( $src_h );
  $w = intval ( $h / $dst_scale );

  $x = ($src_w - $w) / 2;
  $y = 0;
 }
 // 剪裁
 $croped = imagecreatetruecolor ( $w, $h );
 imagecopy ( $croped, $source, 0, 0, $x, $y, $src_w, $src_h );
 // 缩放
 $scale = $option ['width'] / $w;
 $target = imagecreatetruecolor ( $option ['width'], $option ['height'] );
 $final_w = intval ( $w * $scale );
 $final_h = intval ( $h * $scale );
 imagecopyresampled ( $target, $croped, 0, 0, 0, 0, $final_w, $final_h, $w, $h );
 imagedestroy ( $croped );

 //输出(保存)图片
 if (! empty ( $save_img ))
 {

  $org_funcs ['save_func'] ( $target, $save_img );
 } else
 {
  header ( $org_funcs ['header'] );
  $org_funcs ['save_func'] ( $target );
 }
 imagedestroy ( $target );
 return array ('flag' => True, 'msg' => '' );
 }

 /**
 * 
 * 等比例缩放图像
 * @param $src_img 原图片
 * @param $save_img 需要保存的地方
 * @param $option 参数设置 array('width'=>xx,'height'=>xxx)
 * 
 */
 function resize_image($src_img, $save_img = '', $option)
 {
 $org_ext = $this->is_img ( $src_img );
 if (! $org_ext ['flag'])
 {
  return $org_ext;
 }

 //如果有保存路径,则确定路径是否正确
 if (! empty ( $save_img ))
 {
  $f = $this->check_dir ( $save_img );
  if (! $f ['flag'])
  {
  return $f;
  }
 }

 //获取出相应的方法
 $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] );

 //获取原大小
 $source = $org_funcs ['create_func'] ( $src_img );
 $src_w = imagesx ( $source );
 $src_h = imagesy ( $source );

 if (($option ['width'] && $src_w > $option ['width']) || ($option ['height'] && $src_h > $option ['height']))
 {
  if ($option ['width'] && $src_w > $option ['width'])
  {
  $widthratio = $option ['width'] / $src_w;
  $resizewidth_tag = true;
  }

  if ($option ['height'] && $src_h > $option ['height'])
  {
  $heightratio = $option ['height'] / $src_h;
  $resizeheight_tag = true;
  }

  if ($resizewidth_tag && $resizeheight_tag)
  {
  if ($widthratio < $heightratio)
   $ratio = $widthratio;
  else
   $ratio = $heightratio;
  }

  if ($resizewidth_tag && ! $resizeheight_tag)
  $ratio = $widthratio;
  if ($resizeheight_tag && ! $resizewidth_tag)
  $ratio = $heightratio;

  $newwidth = $src_w * $ratio;
  $newheight = $src_h * $ratio;

  if (function_exists ( "imagecopyresampled" ))
  {
  $newim = imagecreatetruecolor ( $newwidth, $newheight );
  imagecopyresampled ( $newim, $source, 0, 0, 0, 0, $newwidth, $newheight, $src_w, $src_h );
  } else
  {
  $newim = imagecreate ( $newwidth, $newheight );
  imagecopyresized ( $newim, $source, 0, 0, 0, 0, $newwidth, $newheight, $src_w, $src_h );
  }
 }
 //输出(保存)图片
 if (! empty ( $save_img ))
 {

  $org_funcs ['save_func'] ( $newim, $save_img );
 } else
 {
  header ( $org_funcs ['header'] );
  $org_funcs ['save_func'] ( $newim );
 }
 imagedestroy ( $newim );
 return array ('flag' => True, 'msg' => '' );
 }

 /**
 * 
 * 生成水印图片
 * @param $org_img 原图像
 * @param $mark_img 水印标记图像
 * @param $save_img 当其目录不存在时,会试着创建目录
 * @param array $option 为水印的一些基本设置包含:
 * x:水印的水平位置,默认为减去水印图宽度后的值
 * y:水印的垂直位置,默认为减去水印图高度后的值
 * alpha:alpha值(控制透明度),默认为50
 */
 public function water_mark($org_img, $mark_img, $save_img = '', $option = array())
 {
 //检查图片
 $org_ext = $this->is_img ( $org_img );
 if (! $org_ext ['flag'])
 {
  return $org_ext;
 }
 $mark_ext = $this->is_img ( $mark_img );
 if (! $mark_ext ['flag'])
 {
  return $mark_ext;
 }
 //如果有保存路径,则确定路径是否正确
 if (! empty ( $save_img ))
 {
  $f = $this->check_dir ( $save_img );
  if (! $f ['flag'])
  {
  return $f;
  }
 }

 //获取相应画布
 $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] );
 $org_img_im = $org_funcs ['create_func'] ( $org_img );

 $mark_funcs = $this->get_img_funcs ( $mark_ext ['msg'] );
 $mark_img_im = $mark_funcs ['create_func'] ( $mark_img );

 //拷贝水印图片坐标
 $mark_img_im_x = 0;
 $mark_img_im_y = 0;
 //拷贝水印图片高宽
 $mark_img_w = imagesx ( $mark_img_im );
 $mark_img_h = imagesy ( $mark_img_im );

 $org_img_w = imagesx ( $org_img_im );
 $org_img_h = imagesx ( $org_img_im );

 //合成生成点坐标
 $x = $org_img_w - $mark_img_w;
 $org_img_im_x = isset ( $option ['x'] ) ? $option ['x'] : $x;
 $org_img_im_x = ($org_img_im_x > $org_img_w or $org_img_im_x < 0) ? $x : $org_img_im_x;
 $y = $org_img_h - $mark_img_h;
 $org_img_im_y = isset ( $option ['y'] ) ? $option ['y'] : $y;
 $org_img_im_y = ($org_img_im_y > $org_img_h or $org_img_im_y < 0) ? $y : $org_img_im_y;

 //alpha
 $alpha = isset ( $option ['alpha'] ) ? $option ['alpha'] : 50;
 $alpha = ($alpha > 100 or $alpha < 0) ? 50 : $alpha;

 //合并图片
 imagecopymerge ( $org_img_im, $mark_img_im, $org_img_im_x, $org_img_im_y, $mark_img_im_x, $mark_img_im_y, $mark_img_w, $mark_img_h, $alpha );

 //输出(保存)图片
 if (! empty ( $save_img ))
 {

  $org_funcs ['save_func'] ( $org_img_im, $save_img );
 } else
 {
  header ( $org_funcs ['header'] );
  $org_funcs ['save_func'] ( $org_img_im );
 }
 //销毁画布
 imagedestroy ( $org_img_im );
 imagedestroy ( $mark_img_im );
 return array ('flag' => True, 'msg' => '' );

 }

 /**
 * 
 * 检查图片
 * @param unknown_type $img_path
 * @return array('flag'=>true/false,'msg'=>ext/错误信息) 
 */
 private function is_img($img_path)
 {
 if (! file_exists ( $img_path ))
 {
  return array ('flag' => False, 'msg' => "加载图片 $img_path 失败!" );
 }
 $ext = explode ( '.', $img_path );
 $ext = strtolower ( end ( $ext ) );
 if (! in_array ( $ext, $this->exts ))
 {
  return array ('flag' => False, 'msg' => "图片 $img_path 格式不正确!" );
 }
 return array ('flag' => True, 'msg' => $ext );
 }

 /**
 * 
 * 返回正确的图片函数
 * @param unknown_type $ext
 */
 private function get_img_funcs($ext)
 {
 //选择
 switch ($ext)
 {
  case 'jpg' :
  $header = 'Content-Type:image/jpeg';
  $createfunc = 'imagecreatefromjpeg';
  $savefunc = 'imagejpeg';
  break;
  case 'jpeg' :
  $header = 'Content-Type:image/jpeg';
  $createfunc = 'imagecreatefromjpeg';
  $savefunc = 'imagejpeg';
  break;
  case 'gif' :
  $header = 'Content-Type:image/gif';
  $createfunc = 'imagecreatefromgif';
  $savefunc = 'imagegif';
  break;
  case 'bmp' :
  $header = 'Content-Type:image/bmp';
  $createfunc = 'imagecreatefrombmp';
  $savefunc = 'imagebmp';
  break;
  default :
  $header = 'Content-Type:image/png';
  $createfunc = 'imagecreatefrompng';
  $savefunc = 'imagepng';
 }
 return array ('save_func' => $savefunc, 'create_func' => $createfunc, 'header' => $header );
 }

 /**
 * 
 * 检查并试着创建目录
 * @param $save_img
 */
 private function check_dir($save_img)
 {
 $dir = dirname ( $save_img );
 if (! is_dir ( $dir ))
 {
  if (! mkdir ( $dir, 0777, true ))
  {
  return array ('flag' => False, 'msg' => "图片保存目录 $dir 无法创建!" );
  }
 }
 return array ('flag' => True, 'msg' => '' );
 }
}

if (! empty ( $_FILES ['test'] ['tmp_name'] ))
{
 //例子
 $img = new Img ();
 //原图
 $name = explode ( '.', $_FILES ['test'] ['name'] );
 $org_img = 'D:/test.' . end ( $name );
 move_uploaded_file ( $_FILES ['test'] ['tmp_name'], $org_img );
 $option = array ('width' => $_POST ['width'], 'height' => $_POST ['height'] );
 if ($_POST ['type'] == 1)
 {
 $s = $img->resize_image ( $org_img, '', $option );
 } else
 {
 $img->thumb_img ( $org_img, '', $option );
 }
 unlink ( $org_img );
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

PHP 相关文章推荐
PHP安全配置
Oct 09 PHP
[原创]PHP中通过ADODB库实现调用Access数据库之修正版本
Dec 31 PHP
深入php中var_dump方法的使用详解
Jun 24 PHP
php ZipArchive压缩函数详解实例
Nov 06 PHP
有关于PHP中常见数据类型的汇总分享
Jan 06 PHP
php数组合并array_merge()函数使用注意事项
Jun 19 PHP
PHP实现获取域名的方法小结
Nov 05 PHP
9条PHP编程小知识及易犯的小错误
Jan 22 PHP
php curl请求信息和返回信息设置代码实例
Apr 27 PHP
PHP全功能无变形图片裁剪操作类与用法示例
Jan 10 PHP
PHP学习笔记之session
May 06 PHP
PHP中md5()函数的用法讲解
Mar 30 PHP
php打造智能化的柱状图程序,用于报表等
Jun 19 #PHP
php实现通过ftp上传文件
Jun 19 #PHP
php结合正则获取字符串中数字
Jun 19 #PHP
php中文验证码实现方法
Jun 18 #PHP
php实现比较两个文件夹异同的方法
Jun 18 #PHP
php判断两个日期之间相差多少个月份的方法
Jun 18 #PHP
php实现转换ubb代码的方法
Jun 18 #PHP
You might like
mysqli_set_charset和SET NAMES使用抉择及优劣分析
2013/01/13 PHP
在IE中调用javascript打开Excel的代码(downmoon原作)
2007/04/02 Javascript
JQuery.ajax传递中文参数的解决方法 推荐
2011/03/28 Javascript
JS通过相同的name进行表格求和代码
2013/08/18 Javascript
FF IE浏览器修改标签透明度的方法
2014/01/27 Javascript
React Native实现地址挑选器功能
2017/10/24 Javascript
详解使用element-ui table组件的筛选功能的一个小坑
2018/11/02 Javascript
vue 插件的方法代码详解
2019/06/06 Javascript
微信小程序引入Vant组件库过程解析
2019/08/06 Javascript
解决vue+ element ui 表单验证有值但验证失败问题
2020/01/16 Javascript
多种类型jQuery网页验证码插件代码实例
2021/01/09 jQuery
[02:13] 完美世界DOTA2联赛PWL DAY5集锦
2020/11/03 DOTA
Python完全新手教程
2007/02/08 Python
python 生成不重复的随机数的代码
2011/05/15 Python
python 七种邮件内容发送方法实例
2014/04/22 Python
Python实现二维有序数组查找的方法
2016/04/27 Python
pandas全表查询定位某个值所在行列的方法
2018/04/12 Python
使用python将图片格式转换为ico格式的示例
2018/10/22 Python
在Python中分别打印列表中的每一个元素方法
2018/11/07 Python
python安装scipy的方法步骤
2019/06/26 Python
python爬虫 基于requests模块的get请求实现详解
2019/08/20 Python
Python使用贪婪算法解决问题
2019/10/22 Python
德国大型的家具商店:Pharao24.de
2016/10/02 全球购物
StubHub新加坡:购买和出售全球活动门票
2017/03/10 全球购物
外贸业务员岗位职责
2013/11/24 职场文书
利群广告词
2014/03/20 职场文书
老公给老婆的保证书
2014/04/28 职场文书
禁止酒驾标语
2014/06/25 职场文书
个人简历自荐信
2014/06/26 职场文书
社区端午节活动总结
2015/02/11 职场文书
2015年清明节网上祭英烈活动总结
2015/03/26 职场文书
2016年基层党组织公开承诺书
2016/03/25 职场文书
导游词之秦始皇兵马俑博物馆
2019/09/29 职场文书
Python进阶学习之带你探寻Python类的鼻祖-元类
2021/05/08 Python
vue报错function () { [native code] },无法出现我们想要的内容 Unknown custom element
2022/04/11 Vue.js
深入理解MySQL中MVCC与BufferPool缓存机制
2022/05/25 MySQL