• PHP GD 库 缩略图 添加水印


      1 class cls_image {
      2     var $error_no = 0;
      3     var $error_msg = '';
      4     //var $images_dir  = IMAGE_DIR;
      5     //var $data_dir    = DATA_DIR;
      6     var $images_dir = GOODS_PATH1;
      7     var $data_dir = GOODS_PATH1;
      8     var $bgcolor = '';
      9     var $type_maping = array(
     10         1 => 'image/gif',
     11         2 => 'image/jpeg',
     12         3 => 'image/png'
     13     );
     14 
     15     function __construct($bgcolor = '') {
     16         $this -> cls_image($bgcolor);
     17     }
     18 
     19     function cls_image($bgcolor = '') {
     20         if ($bgcolor) {
     21             $this -> bgcolor = $bgcolor;
     22         } else {
     23             $this -> bgcolor = "#FFFFFF";
     24         }
     25     }
     26 
     27     /**
     28      * 图片上传的处理函数
     29      *
     30      * @access      public
     31      * @param       array       upload       包含上传的图片文件信息的数组
     32      * @param       array       dir          文件要上传在$this->data_dir下的目录名。如果为空图片放在则在$this->images_dir下以当月命名的目录下
     33      * @param       array       img_name     上传图片名称,为空则随机生成
     34      * @return      mix         如果成功则返回文件名,否则返回false
     35      */
     36     function upload_image($upload, $dir = '', $img_name = '') {
     37         /* 没有指定目录默认为根目录images */
     38         // if (empty($dir))
     39         // {
     40         // /* 创建当月目录 */
     41         // $dir = date('Ym');
     42         // $dir = ROOT_PATH . $this->images_dir . '/' . $dir . '/';
     43         // }
     44         // else
     45         // {
     46         // /* 创建目录 */
     47         // $dir = ROOT_PATH . $this->data_dir . '/' . $dir . '/';
     48         // if ($img_name)
     49         // {
     50         // $img_name = $dir . $img_name; // 将图片定位到正确地址
     51         // }
     52         // }
     53         //
     54         /* 没有指定目录默认为admin/images/static01/goodsimage/image */
     55         if (empty($dir)) {
     56             /* 创建当月目录 */
     57             $dir = date('Ymd');
     58             $dir = ROOT_PATH . $this -> images_dir . '/' . $dir . '/';
     59         } else {
     60             /* 创建目录 */
     61             $dir = ROOT_PATH . $this -> data_dir . '/' . $dir . '/';
     62             if ($img_name) {
     63                 $img_name = $dir . $img_name;
     64                 // 将图片定位到正确地址
     65             }
     66         }
     67 
     68         /* 如果目标目录不存在,则创建它 */
     69         if (!file_exists($dir)) {
     70             if (!make_dir($dir)) {
     71                 /* 创建目录失败 */
     72                 $this -> error_msg = sprintf($GLOBALS['_LANG']['directory_readonly'], $dir);
     73                 $this -> error_no = ERR_DIRECTORY_READONLY;
     74 
     75                 return false;
     76             }
     77         }
     78 
     79         if (empty($img_name)) {
     80 
     81             $img_name = $this -> unique_name($dir);
     82             $img_name = $dir . $img_name . $this -> get_filetype($upload['name']);
     83 
     84         }
     85 
     86         if (!$this -> check_img_type($upload['type'])) {
     87             $this -> error_msg = $GLOBALS['_LANG']['invalid_upload_image_type'];
     88             $this -> error_no = ERR_INVALID_IMAGE_TYPE;
     89             return false;
     90         }
     91 
     92         /* 允许上传的文件类型 */
     93         //$allow_file_types = '|GIF|JPG|JEPG|PNG|BMP|SWF|';
     94         $allow_file_types = '|GIF|JPG|JEPG|BMP|';
     95         if (!check_file_type($upload['tmp_name'], $img_name, $allow_file_types)) {
     96             $this -> error_msg = $GLOBALS['_LANG']['invalid_upload_image_type'];
     97             $this -> error_no = ERR_INVALID_IMAGE_TYPE;
     98             return false;
     99         }
    100 
    101         if ($this -> move_file($upload, $img_name)) {
    102             return str_replace(ROOT_PATH, '', $img_name);
    103 
    104         } else {
    105             $this -> error_msg = sprintf($GLOBALS['_LANG']['upload_failure'], $upload['name']);
    106             $this -> error_no = ERR_UPLOAD_FAILURE;
    107 
    108             return false;
    109         }
    110     }
    111 
    112     /**
    113      * 创建图片的缩略图
    114      *
    115      * @access  public
    116      * @param   string      $img    原始图片的路径
    117      * @param   int         $thumb_width  缩略图宽度
    118      * @param   int         $thumb_height 缩略图高度
    119      * @param   strint      $path         指定生成图片的目录名
    120      * @return  mix         如果成功返回缩略图的路径,失败则返回false
    121      */
    122     function make_thumb($img, $thumb_width = 0, $thumb_height = 0, $path = '', $bgcolor = '', $fileName = "") {
    123         $gd = $this -> gd_version();
    124         //获取 GD 版本。0 表示没有 GD 库,1 表示 GD 1.x,2 表示 GD 2.x
    125         if ($gd == 0) {
    126             $this -> error_msg = $GLOBALS['_LANG']['missing_gd'];
    127             return false;
    128         }
    129 
    130         /* 检查缩略图宽度和高度是否合法 */
    131         if ($thumb_width == 0 && $thumb_height == 0) {
    132             return str_replace(ROOT_PATH, '', str_replace('\', '/', realpath($img)));
    133         }
    134 
    135         /* 检查原始文件是否存在及获得原始文件的信息 */
    136         $org_info = @getimagesize($img);
    137         if (!$org_info) {
    138             $this -> error_msg = sprintf($GLOBALS['_LANG']['missing_orgin_image'], $img);
    139             $this -> error_no = ERR_IMAGE_NOT_EXISTS;
    140 
    141             return false;
    142         }
    143 
    144         if (!$this -> check_img_function($org_info[2])) {
    145             $this -> error_msg = sprintf($GLOBALS['_LANG']['nonsupport_type'], $this -> type_maping[$org_info[2]]);
    146             $this -> error_no = ERR_NO_GD;
    147 
    148             return false;
    149         }
    150 
    151         $img_org = $this -> img_resource($img, $org_info[2]);
    152 
    153         /* 原始图片以及缩略图的尺寸比例 */
    154         $scale_org = $org_info[0] / $org_info[1];
    155         /* 处理只有缩略图宽和高有一个为0的情况,这时背景和缩略图一样大 */
    156         if ($thumb_width == 0) {
    157             $thumb_width = $thumb_height * $scale_org;
    158         }
    159         if ($thumb_height == 0) {
    160             $thumb_height = $thumb_width / $scale_org;
    161         }
    162 
    163         /* 创建缩略图的标志符 */
    164         if ($gd == 2) {
    165             $img_thumb = imagecreatetruecolor($thumb_width, $thumb_height);
    166         } else {
    167             $img_thumb = imagecreate($thumb_width, $thumb_height);
    168         }
    169 
    170         /* 背景颜色 */
    171         if (empty($bgcolor)) {
    172             $bgcolor = $this -> bgcolor;
    173         }
    174         $bgcolor = trim($bgcolor, "#");
    175         sscanf($bgcolor, "%2x%2x%2x", $red, $green, $blue);
    176         $clr = imagecolorallocate($img_thumb, $red, $green, $blue);
    177         imagefilledrectangle($img_thumb, 0, 0, $thumb_width, $thumb_height, $clr);
    178 
    179         if ($org_info[0] / $thumb_width > $org_info[1] / $thumb_height) {
    180             $lessen_width = $thumb_width;
    181             $lessen_height = $thumb_width / $scale_org;
    182         } else {
    183             /* 原始图片比较高,则以高度为准 */
    184             $lessen_width = $thumb_height * $scale_org;
    185             $lessen_height = $thumb_height;
    186         }
    187 
    188         $dst_x = ($thumb_width - $lessen_width) / 2;
    189         $dst_y = ($thumb_height - $lessen_height) / 2;
    190 
    191         /* 将原始图片进行缩放处理 */
    192         if ($gd == 2) {
    193             imagecopyresampled($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]);
    194         } else {
    195             imagecopyresized($img_thumb, $img_org, $dst_x, $dst_y, 0, 0, $lessen_width, $lessen_height, $org_info[0], $org_info[1]);
    196         }
    197 
    198         /* 创建当天目录 */
    199         if (empty($path)) {
    200             //$dir = ROOT_PATH . $this->images_dir . '/' . date('Ym').'/';
    201             /* 创建当天目录 */
    202             $dir = date('Ymd');
    203             $dir = ROOT_PATH . $this -> images_dir . '/' . $dir . '/';
    204         } else {
    205             $dir = $path;
    206         }
    207 
    208         /* 如果目标目录不存在,则创建它 */
    209         if (!file_exists($dir)) {
    210             if (!make_dir($dir)) {
    211                 /* 创建目录失败 */
    212                 $this -> error_msg = sprintf($GLOBALS['_LANG']['directory_readonly'], $dir);
    213                 $this -> error_no = ERR_DIRECTORY_READONLY;
    214                 return false;
    215             }
    216         }
    217 
    218         /* 如果文件名为空,生成不重名随机文件名 */
    219         $filename = $this -> unique_name($dir);
    220         $filename = !empty($fileName) ? $fileName : $filename;
    221 
    222         /* 生成文件 */
    223         if (function_exists('imagejpeg')) {
    224             imagejpeg($img_thumb, $dir . $filename);
    225         } elseif (function_exists('imagegif')) {
    226             imagegif($img_thumb, $dir . $filename);
    227         } elseif (function_exists('imagepng')) {
    228             imagepng($img_thumb, $dir . $filename);
    229         } else {
    230             $this -> error_msg = $GLOBALS['_LANG']['creating_failure'];
    231             $this -> error_no = ERR_NO_GD;
    232 
    233             return false;
    234         }
    235 
    236         imagedestroy($img_thumb);
    237         imagedestroy($img_org);
    238 
    239         //确认文件是否生成
    240         if (file_exists($dir . $filename)) {
    241             return str_replace(ROOT_PATH, '', $dir) . $filename;
    242         } else {
    243             $this -> error_msg = $GLOBALS['_LANG']['writting_failure'];
    244             $this -> error_no = ERR_DIRECTORY_READONLY;
    245 
    246             return false;
    247         }
    248     }
    249 
    250     /**
    251      * 为图片增加水印
    252      *
    253      * @access      public
    254      * @param       string      filename            原始图片文件名,包含完整路径
    255      * @param       string      target_file         需要加水印的图片文件名,包含完整路径。如果为空则覆盖源文件
    256      * @param       string      $watermark          水印完整路径
    257      * @param       int         $watermark_place    水印位置代码
    258      * @return      mix         如果成功则返回文件路径,否则返回false
    259      */
    260     function add_watermark($filename, $target_file = '', $watermark = '', $watermark_place = '', $watermark_alpha = 0.65) {
    261         // 是否安装了GD
    262         $gd = $this -> gd_version();
    263         if ($gd == 0) {
    264             $this -> error_msg = $GLOBALS['_LANG']['missing_gd'];
    265             $this -> error_no = ERR_NO_GD;
    266 
    267             return false;
    268         }
    269 
    270         // 文件是否存在
    271         if ((!file_exists($filename)) || (!is_file($filename))) {
    272             $this -> error_msg = sprintf($GLOBALS['_LANG']['missing_orgin_image'], $filename);
    273             $this -> error_no = ERR_IMAGE_NOT_EXISTS;
    274 
    275             return false;
    276         }
    277 
    278         /* 如果水印的位置为0,则返回原图 */
    279         if ($watermark_place == 0 || empty($watermark)) {
    280             return str_replace(ROOT_PATH, '', str_replace('\', '/', realpath($filename)));
    281         }
    282 
    283         if (!$this -> validate_image($watermark)) {
    284             /* 已经记录了错误信息 */
    285             return false;
    286         }
    287 
    288         // 获得水印文件以及源文件的信息
    289         $watermark_info = @getimagesize($watermark);
    290         $watermark_handle = $this -> img_resource($watermark, $watermark_info[2]);
    291 
    292         if (!$watermark_handle) {
    293             $this -> error_msg = sprintf($GLOBALS['_LANG']['create_watermark_res'], $this -> type_maping[$watermark_info[2]]);
    294             $this -> error_no = ERR_INVALID_IMAGE;
    295 
    296             return false;
    297         }
    298 
    299         // 根据文件类型获得原始图片的操作句柄
    300         $source_info = @getimagesize($filename);
    301         $source_handle = $this -> img_resource($filename, $source_info[2]);
    302         if (!$source_handle) {
    303             $this -> error_msg = sprintf($GLOBALS['_LANG']['create_origin_image_res'], $this -> type_maping[$source_info[2]]);
    304             $this -> error_no = ERR_INVALID_IMAGE;
    305 
    306             return false;
    307         }
    308 
    309         // 根据系统设置获得水印的位置
    310         switch ($watermark_place) {
    311             case '1' :
    312                 $x = 0;
    313                 $y = 0;
    314                 break;
    315             case '2' :
    316                 $x = $source_info[0] - $watermark_info[0];
    317                 $y = 0;
    318                 break;
    319             case '4' :
    320                 $x = 0;
    321                 $y = $source_info[1] - $watermark_info[1];
    322                 break;
    323             case '5' :
    324                 $x = $source_info[0] - $watermark_info[0];
    325                 $y = $source_info[1] - $watermark_info[1];
    326                 break;
    327             default :
    328                 $x = $source_info[0] / 2 - $watermark_info[0] / 2;
    329                 $y = $source_info[1] / 2 - $watermark_info[1] / 2;
    330         }
    331 
    332         if (strpos(strtolower($watermark_info['mime']), 'png') !== false) {
    333             imageAlphaBlending($watermark_handle, true);
    334             imagecopy($source_handle, $watermark_handle, $x, $y, 0, 0, $watermark_info[0], $watermark_info[1]);
    335         } else {
    336             imagecopymerge($source_handle, $watermark_handle, $x, $y, 0, 0, $watermark_info[0], $watermark_info[1], $watermark_alpha);
    337         }
    338         $target = empty($target_file) ? $filename : $target_file;
    339 
    340         switch ($source_info[2] ) {
    341             case 'image/gif' :
    342             case 1 :
    343                 imagegif($source_handle, $target);
    344                 break;
    345 
    346             case 'image/pjpeg' :
    347             case 'image/jpeg' :
    348             case 2 :
    349                 imagejpeg($source_handle, $target);
    350                 break;
    351 
    352             case 'image/x-png' :
    353             case 'image/png' :
    354             case 3 :
    355                 imagepng($source_handle, $target);
    356                 break;
    357 
    358             default :
    359                 $this -> error_msg = $GLOBALS['_LANG']['creating_failure'];
    360                 $this -> error_no = ERR_NO_GD;
    361 
    362                 return false;
    363         }
    364 
    365         imagedestroy($source_handle);
    366 
    367         $path = realpath($target);
    368         if ($path) {
    369             return str_replace(ROOT_PATH, '', str_replace('\', '/', $path));
    370         } else {
    371             $this -> error_msg = $GLOBALS['_LANG']['writting_failure'];
    372             $this -> error_no = ERR_DIRECTORY_READONLY;
    373 
    374             return false;
    375         }
    376     }
    377 
    378     /**
    379      *  检查水印图片是否合法
    380      *
    381      * @access  public
    382      * @param   string      $path       图片路径
    383      *
    384      * @return boolen
    385      */
    386     function validate_image($path) {
    387         if (empty($path)) {
    388             $this -> error_msg = $GLOBALS['_LANG']['empty_watermark'];
    389             $this -> error_no = ERR_INVALID_PARAM;
    390 
    391             return false;
    392         }
    393 
    394         /* 文件是否存在 */
    395         if (!file_exists($path)) {
    396             $this -> error_msg = sprintf($GLOBALS['_LANG']['missing_watermark'], $path);
    397             $this -> error_no = ERR_IMAGE_NOT_EXISTS;
    398             return false;
    399         }
    400 
    401         // 获得文件以及源文件的信息
    402         $image_info = @getimagesize($path);
    403 
    404         if (!$image_info) {
    405             $this -> error_msg = sprintf($GLOBALS['_LANG']['invalid_image_type'], $path);
    406             $this -> error_no = ERR_INVALID_IMAGE;
    407             return false;
    408         }
    409 
    410         /* 检查处理函数是否存在 */
    411         if (!$this -> check_img_function($image_info[2])) {
    412             $this -> error_msg = sprintf($GLOBALS['_LANG']['nonsupport_type'], $this -> type_maping[$image_info[2]]);
    413             $this -> error_no = ERR_NO_GD;
    414             return false;
    415         }
    416 
    417         return true;
    418     }
    419 
    420     /**
    421      * 返回错误信息
    422      *
    423      * @return  string   错误信息
    424      */
    425     function error_msg() {
    426         return $this -> error_msg;
    427     }
    428 
    429     /*------------------------------------------------------ */
    430     //-- 工具函数
    431     /*------------------------------------------------------ */
    432 
    433     /**
    434      * 检查图片类型
    435      * @param   string  $img_type   图片类型
    436      * @return  bool
    437      */
    438     function check_img_type($img_type) {
    439         return $img_type == 'image/pjpeg' || $img_type == 'image/x-png' || $img_type == 'image/png' || $img_type == 'image/gif' || $img_type == 'image/jpeg';
    440     }
    441 
    442     /**
    443      * 检查图片处理能力
    444      *
    445      * @access  public
    446      * @param   string  $img_type   图片类型
    447      * @return  void
    448      */
    449     function check_img_function($img_type) {
    450         switch ($img_type) {
    451             case 'image/gif' :
    452             case 1 :
    453                 if (PHP_VERSION >= '4.3') {
    454                     return function_exists('imagecreatefromgif');
    455                 } else {
    456                     return (imagetypes() & IMG_GIF) > 0;
    457                 }
    458                 break;
    459 
    460             case 'image/pjpeg' :
    461             case 'image/jpeg' :
    462             case 2 :
    463                 if (PHP_VERSION >= '4.3') {
    464                     return function_exists('imagecreatefromjpeg');
    465                 } else {
    466                     return (imagetypes() & IMG_JPG) > 0;
    467                 }
    468                 break;
    469 
    470             case 'image/x-png' :
    471             case 'image/png' :
    472             case 3 :
    473                 if (PHP_VERSION >= '4.3') {
    474                     return function_exists('imagecreatefrompng');
    475                 } else {
    476                     return (imagetypes() & IMG_PNG) > 0;
    477                 }
    478                 break;
    479 
    480             default :
    481                 return false;
    482         }
    483     }
    484 
    485     /**
    486      * 生成随机的数字串
    487      *
    488      * @author: weber liu
    489      * @return string
    490      */
    491     function random_filename() {
    492         $str = '';
    493         for ($i = 0; $i < 9; $i++) {
    494             $str .= mt_rand(0, 9);
    495         }
    496 
    497         return time() . $str;
    498     }
    499 
    500     /**
    501      *  生成指定目录不重名的文件名
    502      *
    503      * @access  public
    504      * @param   string      $dir        要检查是否有同名文件的目录
    505      *
    506      * @return  string      文件名
    507      */
    508     function unique_name($dir) {
    509         $filename = '';
    510         while (empty($filename)) {
    511             $filename = cls_image::random_filename();
    512             if (file_exists($dir . $filename . '.jpg') || file_exists($dir . $filename . '.gif') || file_exists($dir . $filename . '.png')) {
    513                 $filename = '';
    514             }
    515         }
    516 
    517         return $filename;
    518     }
    519 
    520     /**
    521      *  返回文件后缀名,如‘.php’
    522      *
    523      * @access  public
    524      * @param
    525      *
    526      * @return  string      文件后缀名
    527      */
    528     function get_filetype($path) {
    529         $pos = strrpos($path, '.');
    530         if ($pos !== false) {
    531             return substr($path, $pos);
    532         } else {
    533             return '';
    534         }
    535     }
    536 
    537     /**
    538      * 根据来源文件的文件类型创建一个图像操作的标识符
    539      *
    540      * @access  public
    541      * @param   string      $img_file   图片文件的路径
    542      * @param   string      $mime_type  图片文件的文件类型
    543      * @return  resource    如果成功则返回图像操作标志符,反之则返回错误代码
    544      */
    545     function img_resource($img_file, $mime_type) {
    546         switch ($mime_type) {
    547             case 1 :
    548             case 'image/gif' :
    549                 $res = imagecreatefromgif($img_file);
    550                 break;
    551 
    552             case 2 :
    553             case 'image/pjpeg' :
    554             case 'image/jpeg' :
    555                 $res = imagecreatefromjpeg($img_file);
    556                 break;
    557 
    558             case 3 :
    559             case 'image/x-png' :
    560             case 'image/png' :
    561                 $res = imagecreatefrompng($img_file);
    562                 break;
    563 
    564             default :
    565                 return false;
    566         }
    567 
    568         return $res;
    569     }
    570 
    571     /**
    572      * 获得服务器上的 GD 版本
    573      *
    574      * @access      public
    575      * @return      int         可能的值为0,1,2
    576      */
    577     function gd_version() {
    578         static $version = -1;
    579 
    580         if ($version >= 0) {
    581             return $version;
    582         }
    583 
    584         if (!extension_loaded('gd')) {
    585             $version = 0;
    586         } else {
    587             // 尝试使用gd_info函数
    588             if (PHP_VERSION >= '4.3') {
    589                 if (function_exists('gd_info')) {
    590                     $ver_info = gd_info();
    591                     preg_match('/d/', $ver_info['GD Version'], $match);
    592                     $version = $match[0];
    593                 } else {
    594                     if (function_exists('imagecreatetruecolor')) {
    595                         $version = 2;
    596                     } elseif (function_exists('imagecreate')) {
    597                         $version = 1;
    598                     }
    599                 }
    600             } else {
    601                 if (preg_match('/phpinfo/', ini_get('disable_functions'))) {
    602                     /* 如果phpinfo被禁用,无法确定gd版本 */
    603                     $version = 1;
    604                 } else {
    605                     // 使用phpinfo函数
    606                     ob_start();
    607                     phpinfo(8);
    608                     $info = ob_get_contents();
    609                     ob_end_clean();
    610                     $info = stristr($info, 'gd version');
    611                     preg_match('/d/', $info, $match);
    612                     $version = $match[0];
    613                 }
    614             }
    615         }
    616 
    617         return $version;
    618     }
    619 
    620     /**
    621      *
    622      *
    623      * @access  public
    624      * @param
    625      *
    626      * @return void
    627      */
    628     function move_file($upload, $target) {
    629         if (isset($upload['error']) && $upload['error'] > 0) {
    630             return false;
    631         }
    632 
    633         if (!move_upload_file($upload['tmp_name'], $target)) {
    634             return false;
    635         }
    636 
    637         return true;
    638     }
    639 
    640 }

    调用方法:

     1 try {
     2                 $tempObj = new cls_image();
     3             } catch (Exception $e) {
     4             
     5             }
     6 /**
     7      * 创建图片的缩略图
     8      *
     9      * @access  public
    10      * @param   string      $img    原始图片的路径
    11      * @param   int         $thumb_width  缩略图宽度
    12      * @param   int         $thumb_height 缩略图高度
    13      * @param   strint      $path         指定生成图片的目录名
    14      * @return  mix         如果成功返回缩略图的路径,失败则返回false
    15      */
    16 $press_img = $tempObj->make_thumb($file_path,600,0,$save_path,"",$press_file_name);//创建图片的缩略图
    17 /**
    18      * 为图片增加水印
    19      *
    20      * @access      public
    21      * @param       string      filename            原始图片文件名,包含完整路径
    22      * @param       string      target_file         需要加水印的图片文件名,包含完整路径。如果为空则覆盖源文件
    23      * @param       string      $watermark          水印完整路径
    24      * @param       int         $watermark_place    水印位置代码
    25      * @return      mix         如果成功则返回文件路径,否则返回false
    26      */
    27 $file_path_shuiyin = $tempObj->add_watermark($press0_img , $file_path_shuiyin , $shuiyin_path , 3);
  • 相关阅读:
    Yahoo军规的学习
    从github上拉取代码速度慢的解决方案
    hosts文件介绍
    Windows系统下用nginx服务器部署页面
    前端开发面试题
    IDEA中maven无法拉下依赖问题的解决
    利用补丁永久破解IDEA
    OC项目中常用第三方库和框架介绍
    [暑假集训]开训复健练习赛 G
    [暑假集训]开训复健练习赛 D
  • 原文地址:https://www.cnblogs.com/chuanheng/p/3607935.html
Copyright © 2020-2023  润新知