PHPMailer邮件类邮件发送

 更新时间:2016年11月25日 16:57  点击:1969
本款邮件发送功能我们是用了国外一个开源码的邮件类,大家都可能用过的PHPMailer邮件类很简单,今天来讲一下简单的使用教程,有需要的朋友可以参考下,同时像其它的附件什么的,各位朋友可以给我意见哦。

要注意的内容:
  1. 邮件的字符集设置, $mail->CharSet = "GB2312";            // 这里指定字符集!在这里我只指定为GB2312因为这样Outlook能正常显示邮件主题,我尝试过设为utf-8但在Outlook下显示乱码。
  2. 如果是发送html格式的邮件,那么记得也指定<meta ... charset=GB2312">
  3. 如果你想用它来群发邮件的话,记得修改包含文件函数,如:
  require("phpmailer/class.phpmailer.php");
  改为
  require_once("phpmailer/class.phpmailer.php");
  否则的话会产生类的重定义。

 

 代码如下 复制代码

<?php
/*******************************
*    作者:李英江
* 日期:2006-12-7
*******************************/
require("phpmailer/class.phpmailer.php");
function smtp_mail ( $sendto_email, $subject, $body, $extra_hdrs, $user_name) {
$mail = new PHPMailer();
$mail->IsSMTP();                // send via SMTP
$mail->Host = "200.162.244.66"; // SMTP servers
$mail->SMTPAuth = true;         // turn on SMTP authentication
$mail->Username = "yourmail";   // SMTP username  注意:普通邮件认证不需要加 @域名
$mail->Password = "mailPassword";        // SMTP password
$mail->From = "yourmail@cgsir.com";      // 发件人邮箱
$mail->FromName =  "cgsir.com管理员";  // 发件人

$mail->CharSet = "GB2312";            // 这里指定字符集!
$mail->Encoding = "base64";
$mail->AddAddress($sendto_email,"username");  // 收件人邮箱和姓名
$mail->AddReplyTo("yourmail@cgsir.com","cgsir.com");
//$mail->WordWrap = 50; // set word wrap
//$mail->AddAttachment("/var/tmp/file.tar.gz"); // attachment
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg");
$mail->IsHTML(true);  // send as HTML
        // 邮件主题
$mail->Subject = $subject;
// 邮件内容
$mail->Body = '
<html><head>
<meta http-equiv="Content-Language" content="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>
<body>
        欢迎来到<a href="http://www.111cn.net">http://www.111cn.net</a> <br /><br />
感谢您注册为本站会员!<br /><br />
</body>
</html>
';                                                                      
$mail->AltBody ="text/html";
if(!$mail->Send())
{
  echo "邮件发送有误 <p>";
  echo "邮件错误信息: " . $mail->ErrorInfo;
  exit;
}
else {
  echo "$user_name 邮件发送成功!<br />";
}
}
// 参数说明(发送到, 邮件主题, 邮件内容, 附加信息, 用户名)
smtp_mail('yourmail@cgsir.com', '欢迎来到cgsir.com!', 'NULL', 'cgsir.com', 'username');
?>

需要下载PHPMailer文件包phpmailer-1.73.tar.gz   来自开源社区: http://phpmailer.sourceforge.net/

我们经常在对图像操作时会要有水印 略缩图并且水印可以指定到可以选,1代表左上,2代表左中,3代表左右,4代表中左,5代表中中,6代表中右,7代表下做,8代表下中,9代表下右,0代表随机位置
 代码如下 复制代码

<?php
/*已知问题:1.在图片缩放功能中,使用imagecreatetruecolor函数创建画布,并使用透明处理算法,但PNG格式的图片无法透明。用imagecreate函数创建画布可以解决这个问题,但是缩放出来的图片色数太少了
*
*
*type值:
* (1):代表使用图片缩放功能,此时,$value1代表缩放后图片的宽度,$value2代表缩放后图片的高度
* (2):代表使用图片裁剪功能,此时,$value1代表裁剪开始点的坐标,例:从原点开始即是“0,0”前面是x轴后面是y轴,中间用,分隔,$value2代表裁剪的宽度和高度,同样也是“20,20”的形式使用
* (3):代表使用加图片水印功能,此时,$value1代表水印图片的文件名,$value2代表水印在图片中的位置,有10值个可以选,1代表左上,2代表左中,3代表左右,4代表中左,5代表中中,6代表中右,7代表下做,8代表下中,9代表下右,0代表随机位置
*
*/
class image{
private $types; //使用的功能编号,1为图片缩放功能 2为图片裁剪功能 3,为图片加图片水印功能
private $imgtype;//图片的格式
private $image; //图片资源
private $width;//图片宽度
private $height;//图片高度
private $value1;//根据所传type值的不同,$value1分别代表不同的值
private $value2;//根据所传type值的不同,$value2分别代表不同的值
private $endaddress;//输出后的地址+文件名
function __construct($imageaddress, $types, $value1="", $value2="", $endaddress){
$this->types=$types;
$this->image=$this->imagesources($imageaddress);
$this->width=$this->imagesizex();
$this->height=$this->imagesizey();
$this->value1=$value1;
$this->value2=$value2;
$this->endaddress=$endaddress;
}
function outimage(){ //根据传入type值的不同,输出不同的功能
switch($this->types){
case 1:
$this->scaling();
break;
case 2:
$this->clipping();
break;
case 3:
$this->imagewater();
break;
default:
return false;
}
}
private function imagewater(){ //加图片水印功能
//用函数获取水印文件的长和宽
$imagearrs=$this->getimagearr($this->value1);
//调用函数计算出水印加载的位置
$positionarr=$this->position($this->value2, $imagearrs[0], $imagearrs[1]);
//加水印
imagecopy($this->image, $this->imagesources($this->value1), $positionarr[0], $positionarr[1], 0, 0, $imagearrs[0], $imagearrs[1]);
//调用输出方法保存
$this->output($this->image);
}
private function clipping(){ //图片裁剪功能
//将传进来的值分别赋给变量
list($src_x, $src_y)=explode(",", $this->value1);
list($dst_w, $dst_h)=explode(",", $this->value2);
if($this->width < $src_x+$dst_w || $this->height < $src_y+$dst_h){ //这个判断就是限制不能截取到图片外面去
return false;
}
//创建新的画布资源
$newimg=imagecreatetruecolor($dst_w, $dst_h);
//进行裁剪
imagecopyresampled($newimg, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $dst_w, $dst_h);
//调用输出方法保存
$this->output($newimg);
}
private function scaling(){ //图片缩放功能
//获取等比缩放的宽和高
$this-> proimagesize();
//根据参数进行缩放,并调用输出函数保存处理后的文件
$this->output($this->imagescaling());
}
private function imagesources($imgad){ //获取图片类型并打开图像资源
$imagearray=$this->getimagearr($imgad);
switch($imagearray[2]){
case 1://gif
$this->imgtype=1;
$img=imagecreatefromgif($imgad);
break;
case 2://jpeg
$this->imgtype=2;
$img=imagecreatefromjpeg($imgad);
break;
case 3://png
$this->imgtype=3;
$img=imagecreatefrompng($imgad);
break;
default:
return false;
}
return $img;
}
private function imagesizex(){ //获得图片宽度
return imagesx($this->image);
}
private function imagesizey(){ //获取图片高度
return imagesy($this->image);
}
private function proimagesize(){ //计算等比缩放的图片的宽和高
if($this->value1 && ($this->width < $this->height)) { //等比缩放算法
$this->value1=round(($this->value2/ $this->height)*$this->width);
}else{
$this->value2=round(($this->value1/ $this->width) * $this->height);
}
}
private function imagescaling(){//图像缩放功能,返回处理后的图像资源
$newimg=imagecreatetruecolor($this->value1, $this->value2);
$tran=imagecolortransparent($this->image);//处理透明算法
if($tran >= 0 && $tran < imagecolorstotal($this->image)){
$tranarr=imagecolorsforindex($this->image, $tran);
$newcolor=imagecolorallocate($newimg, $tranarr['red'], $tranarr['green'], $tranarr['blue']);
imagefill($newimg, 0, 0, $newcolor);
imagecolortransparent($newimg, $newcolor);
}
imagecopyresampled($newimg, $this->image, 0, 0, 0, 0, $this->value1, $this->value2, $this->width, $this->height);
return $newimg;
}
private function output($image){//输出图像
switch($this->imgtype){
case 1:
imagegif($image, $this->endaddress);
break;
case 2:
imagejpeg($image, $this->endaddress);
break;
case 3:
imagepng($image, $this->endaddress);
break;
default:
return false;
}
}
private function getimagearr($imagesou){//返回图像属性数组方法
return getimagesize($imagesou);
}
private function position($num, $width, $height){//根据传入的数字返回一个位置的坐标,$width和$height分别代表插入图像的宽和高
switch($num){
case 1:
$positionarr[0]=0;
$positionarr[1]=0;
break;
case 2:
$positionarr[0]=($this->width-$width)/2;
$positionarr[1]=0;
break;
case 3:
$positionarr[0]=$this->width-$width;
$positionarr[1]=0;
break;
case 4:
$positionarr[0]=0;
$positionarr[1]=($this->height-$height)/2;
break;
case 5:
$positionarr[0]=($this->width-$width)/2;
$positionarr[1]=($this->height-$height)/2;
break;
case 6:
$positionarr[0]=$this->width-$width;
$positionarr[1]=($this->height-$height)/2;
break;
case 7:
$positionarr[0]=0;
$positionarr[1]=$this->height-$height;
break;
case 8:
$positionarr[0]=($this->width-$width)/2;
$positionarr[1]=$this->height-$height;
break;
case 9:
$positionarr[0]=$this->width-$width;
$positionarr[1]=$this->height-$height;
break;
case 0:
$positionarr[0]=rand(0, $this->width-$width);
$positionarr[1]=rand(0, $this->height-$height);
break;
}
return $positionarr;
}
function __destruct(){
imagedestroy($this->image);
}
}
?>
从国外网站找到的一款php生成缩略图代码,有需要的朋友可以参考一下。
 代码如下 复制代码
<?php
 
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
 
class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }     
 
}
?>


Usage
Save the above file as SimpleImage.php and take a look at the following examples of how to use the script.

The first example below will load a file named picture.jpg resize it to 250 pixels wide and 400 pixels high and resave it as picture2.jpg

 代码如下 复制代码

<?php
   include('SimpleImage.php');
   $image = new SimpleImage();
   $image->load('picture.jpg');
   $image->resize(250,400);
   $image->save('picture2.jpg');
?>

If you want to resize to a specifed width but keep the dimensions ratio the same then the script can work out the required height for you, just use the resizeToWidth function

 代码如下 复制代码

<?php
   include('SimpleImage.php');
   $image = new SimpleImage();
   $image->load('picture.jpg');
   $image->resizeToWidth(250);
   $image->save('picture2.jpg');
?>

一款实现的生成小图功能的实现代码,有需要的朋友可以参考,每个都有详细的说明参数。
 代码如下 复制代码

<form action="uploads.php" method="post" enctype="multipart/form-data">
 <input type='file' name='image'><br>
 <input type='submit' name='sub' value='提交'>
</form>

uploads.php文件

<?php
class image_upload{
 private $srcimg;  //原图片
 private $destimg;  // 目标图片
 private $width;   //原图片的宽度
 private $height;  //原图片的高度
 private $type;   //原文件的图片类型
 private $thumb_width;  //缩略图的宽度
 private $thumb_height; //缩略图的高度
 private $cut;   //是否剪切图片到指定高度
 private $tmp;   //上传图片的临时地址
 private $error;
 private $im;   // 创建一个临时的图片句柄
 private $new_name;  //上传文件的新名字
 
 function __construct($srcimg,$t_width,$t_height,$cut,$tmp,$error){
  $this->srcimg=$srcimg;
  $this->thumb_width=$t_width;
  $this->thumb_height=$t_height;
  $this->cut=$cut;
  $this->tmp=$tmp;
  $this->error=$error;
  $this->get_srcimg_type();
  $this->get_new_upload_name();
  

   }
  
 function img_upload(){
  //文件上传的方法 
  $this->check_error($this->error);
  $this->in_type();
  $dst_dir='./images';
  if(!is_dir($dst_dir)){
   mkdir($dst_dir);
   echo "%%%<BR>";
  }
  
  if(is_uploaded_file($this->tmp)){
   if(move_uploaded_file($this->tmp, $this->new_name)){
    echo "文件上传成功<br>";
    return true;
   }else{
    echo '文件不能被移动,上传失败';
    exit;
   }
  }else{
    echo '文件上传可能被攻击';
    exit;
  }
  
 }
 
 function make_thumbnail(){
  //生成缩略图的方法
  $this->get_dest_imgpath();
  $this->make_im();
  $this->width=imagesx($this->im);
  $this->height=imagesy($this->im);
  
  $thumb_ratio=$this->thumb_width/$this->thumb_height;
  $ratio=$this->width/$this->height;
  
  
  if($this->cut==1){  //是否裁剪
    if($ratio>=$thumb_ratio){
     $img=imagecreatetruecolor($this->thumb_width, $this->thumb_height);
     imagecopyresampled($img, $this->im, 0, 0, 0, 0, $this->thumb_width, $this->thumb_height, $this->height*$thumb_ratio, $this->height);
     imagejpeg($img,$this->destimg);       
     echo "缩略图生成成功";
    }else{
     $img=imagecreatetruecolor($this->thumb_width, $this->thumb_height);
     imagecopyresampled($img, $this->im, 0, 0, 0, 0, $this->thumb_width, $this->thumb_height, $this->width, $this->width/$thumb_ratio);
     imagejpeg($img,$this->destimg);       
     echo "缩略图生成成功";  
    }
  }else{
   if($ratio>=$thumb_ratio){
     $img=imagecreatetruecolor($this->thumb_height*$thumb_ratio, $this->thumb_height);
     imagecopyresampled($img, $this->im, 0, 0, 0, 0, $this->thumb_height*$thumb_ratio, $this->thumb_height, $this->width, $this->height);
     imagejpeg($img,$this->destimg);       
     echo "缩略图生成成功";
   }else{
     $img=imagecreatetruecolor($this->thumb_width, $this->thumb_width/$thumb_ratio);
     imagecopyresampled($img, $this->im, 0, 0, 0, 0, $this->thumb_width, $this->thumb_width/$thumb_ratio, $this->width, $this->height);
     imagejpeg($img,$this->destimg);       
     echo "缩略图生成成功";
   }
  }
  imagedestroy($this->im);
  imagedestroy($img);
 }
 
 private function check_error($error){
  //检查文件上传传得错误;
  if($error>0){
   switch($error){
    case 1:
     echo "上传文件的大小超过了PHP.INI文件中得配置<br>";
     break;
    case 2:
     echo "上传文件的大小超过了表单中的限制大小<br>";
     break;
    case 3:
     echo "只有部分文件被上传<br>";
     break;
    case 4:
     echo "没有文件被上传<br>";
     break;
    case 6:
     echo "php.ini中没有设置图片存放的临时未知<br>";
     break;
    case 7:
     echo "硬盘不可以写入,上传失败<br>";
     break;
    default:
     echo "未知错误";
     break;
   }
  }
 }
 
 private function get_srcimg_type(){
  //判断源文件的图片类型
  $this->type=substr(strrchr($this->srcimg, '.'),'1');
 }
 
 private function in_type(){
  //检查文件是否符合类型
  $type_arr=array('gif','jpg','png');
  if(!in_array($this->type, $type_arr)){
   echo "只支持PNG,GIF,JPG 三种类型的文件格式……,请重新上传正确的格式";
   exit;
  }
 }
 
 private function get_new_upload_name(){
  //上传的文件生成新的名字
  $this->new_name='images/'.date('YmdHis').'.'.$this->type;
 
 }
 private function make_im(){
  //从原文件新建一幅图像
  switch($this->type){
   case 'jpg':
    $this->im=imagecreatefromjpeg($this->new_name);
    break;
   case 'gif':
    $this->im=imagecreatefromgif($this->new_name);
    break;
   case 'png':
    $this->im=imagecreatefrompng($this->new_name);
    break;
   } 
 }
 private function  get_dest_imgpath(){
  //得到缩略图的存储路径
  $len1=strlen($this->new_name);
  $len2=strlen(strrchr($this->new_name,'.'));
  $len3=$len1-$len2;
  $this->destimg=substr($this->new_name,0,$len3).'_small.'.$this->type;
 }
 
}
 print_r($_FILES);
 $file=$_FILES['image'];
echo $file['name'];
 $uploads=new image_upload($file['name'], 120, 160, 1,  $file['tmp_name'],$file['error'] );
  if($uploads->img_upload()){
   $uploads->make_thumbnail();
  }
 
?>


 

php教程上传图片后,自动裁剪成缩略图,宽不限高

<?php
// $Id: image.php 1937 2009-01-05 19:09:40Z dualface $

/**
* 定义 Helper_Image 类和 Helper_ImageGD 类
*
* @link http://qeephp.com/
* @copyright Copyright (c) 2006-2009 Qeeyuan Inc. {@link http://www.qeeyuan.com}
* @license New BSD License {@link http://qeephp.com/license/}
* @version $Id: image.php 1937 2009-01-05 19:09:40Z dualface $
* @package helper
*/

/**
* Helper_Image 类封装了针对图像的操作
*
* 开发者不能直接构造该类的实例,而是应该用 Helper_Image::createFromFile()
* 静态方法创建一个 Image 类的实例。
*
* 操作大图片时,请确保 php 能够分配足够的内存。
*
* @author YuLei Liao <liaoyulei@qeeyuan.com>
* @version $Id: image.php 1937 2009-01-05 19:09:40Z dualface $
* @package helper
*/
abstract class Helper_Image
{
    /**
     * 从指定文件创建 Helper_ImageGD 对象
     *
     * 用法:
     * @code php
     * $image = Helper_Image::createFromFile('1.jpg');
     * $image->resize($width, $height);
     * $image->saveAsJpeg('2.jpg');
     * @endcode
     *
     * 对于上传的文件,由于其临时文件名中并没有包含扩展名。
     * 因此需要采用下面的方法创建 Image 对象:
     *
     * @code php
     * $ext = pathinfo($_FILES['postfile']['name'], PATHINFO_EXTENSION);
     * $image = Image::createFromFile($_FILES['postfile']['tmp_name'], $ext);
     * @endcode
     *
     * @param string $filename 图像文件的完整路径
     * @param string $fileext 指定扩展名
     *
     * @return Helper_ImageGD 从文件创建的 Helper_ImageGD 对象
     * @throw Q_NotImplementedException
     */
    static function createFromFile($filename, $fileext)
    {
        $fileext = trim(strtolower($fileext), '.');
        $ext2functions = array(
            'jpg'  => 'imagecreatefromjpeg',
            'jpeg' => 'imagecreatefromjpeg',
            'png'  => 'imagecreatefrompng',
            'gif'  => 'imagecreatefromgif'
        );

        if (!isset($ext2functions[$fileext]))
        {
                throw new Q_NotImplementedException(__('imagecreateform' . $fileext));
        }

        $handle = call_user_func($ext2functions[$fileext], $filename);
        return new Helper_ImageGD($handle);
    }

        /**
         * 将 16 进制颜色值转换为 rgb 值
     *
     * 用法:
     * @code php
     * $color = '#369';
     * list($r, $g, $b) = Helper_Image::hex2rgb($color);
     * echo "red: {$r}, green: {$g}, blue: {$b}";
     * @endcode
     *
     * @param string $color 颜色值
     * @param string $default 使用无效颜色值时返回的默认颜色
         *
         * @return array 由 RGB 三色组成的数组
         */
        static function hex2rgb($color, $default = 'ffffff')
        {
        $hex = trim($color, '#&Hh');
        $len = strlen($hex);
        if ($len == 3)
        {
            $hex = "{$hex[0]}{$hex[0]}{$hex[1]}{$hex[1]}{$hex[2]}{$hex[2]}";
        }
        elseif ($len < 6)
        {
            $hex = $default;
        }
        $dec = hexdec($hex);
        return array(($dec >> 16) & 0xff, ($dec >> 8) & 0xff, $dec & 0xff);
        }
}

/**
* Helper_ImageGD 类封装了一个 gd 句柄,用于对图像进行操作
*
* @author YuLei Liao <liaoyulei@qeeyuan.com>
* @version $Id: image.php 1937 2009-01-05 19:09:40Z dualface $
* @package helper
*/
class Helper_ImageGD
{
    /**
     * GD 资源句柄
     *
     * @var resource
     */
    protected $_handle = null;

    /**
     * 构造函数
     *
     * @param resource $handle GD 资源句柄
     */
    function __construct($handle)
    {
        $this->_handle = $handle;
    }

    /**
     * 析构函数
     */
    function __destruct()
    {
            $this->destroy();
    }

    /**
     * 快速缩放图像到指定大小(质量较差)
     *
     * @param int $width 新的宽度
     * @param int $height 新的高度
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function resize($width, $height)
    {
        if (is_null($this->_handle)) return $this;

        $dest = imagecreatetruecolor($width, $height);
        imagecopyresized($dest, $this->_handle, 0, 0, 0, 0,
            $width, $height,
            imagesx($this->_handle), imagesy($this->_handle));
        imagedestroy($this->_handle);
        $this->_handle = $dest;
        return $this;
    }

    /**
     * 缩放图像到指定大小(质量较好,速度比 resize() 慢)
     *
     * @param int $width 新的宽度
     * @param int $height 新的高度
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function resampled($width, $height)
    {
        if (is_null($this->_handle)) return $this;
        $dest = imagecreatetruecolor($width, $height);
        imagecopyresampled($dest, $this->_handle, 0, 0, 0, 0,
            $width, $height,
            imagesx($this->_handle), imagesy($this->_handle));
        imagedestroy($this->_handle);
        $this->_handle = $dest;
        return $this;
    }

    /**
     * 调整图像大小,但不进行缩放操作
     *
     * 用法:
     * @code php
     * $image->resizeCanvas($width, $height, 'top-left');
     * @endcode
     *
     * $pos 参数指定了调整图像大小时,图像内容按照什么位置对齐。
     * $pos 参数的可用值有:
     *
     * -   left: 左对齐
     * -   right: 右对齐
     * -   center: 中心对齐
     * -   top: 顶部对齐
     * -   bottom: 底部对齐
     * -   top-left, left-top: 左上角对齐
     * -   top-right, right-top: 右上角对齐
     * -   bottom-left, left-bottom: 左下角对齐
     * -   bottom-right, right-bottom: 右下角对齐
     *
     * 如果指定了无效的 $pos 参数,则等同于指定 center。
     *
     * @param int $width 新的高度
     * @param int $height 新的宽度
     * @param string $pos 调整时图像位置的变化
     * @param string $bgcolor 空白部分的默认颜色
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function resizeCanvas($width, $height, $pos = 'center', $bgcolor = '0xffffff')
    {
        if (is_null($this->_handle)) return $this;

        $dest = imagecreatetruecolor($width, $height);
        $sx = imagesx($this->_handle);
        $sy = imagesy($this->_handle);

        // 根据 pos 属性来决定如何定位原始图片
        switch (strtolower($pos))
        {
        case 'left':
            $ox = 0;
            $oy = ($height - $sy) / 2;
            break;
        case 'right':
            $ox = $width - $sx;
            $oy = ($height - $sy) / 2;
            break;
        case 'top':
            $ox = ($width - $sx) / 2;
            $oy = 0;
            break;
        case 'bottom':
            $ox = ($width - $sx) / 2;
            $oy = $height - $sy;
            break;
        case 'top-left':
        case 'left-top':
            $ox = $oy = 0;
            break;
        case 'top-right':
        case 'right-top':
            $ox = $width - $sx;
            $oy = 0;
            break;
        case 'bottom-left':
        case 'left-bottom':
            $ox = 0;
            $oy = $height - $sy;
            break;
        case 'bottom-right':
        case 'right-bottom':
            $ox = $width - $sx;
            $oy = $height - $sy;
            break;
        default:
            $ox = ($width - $sx) / 2;
            $oy = ($height - $sy) / 2;
        }

        list ($r, $g, $b) = Helper_Image::hex2rgb($bgcolor, '0xffffff');
        $bgcolor = imagecolorallocate($dest, $r, $g, $b);
        imagefilledrectangle($dest, 0, 0, $width, $height, $bgcolor);
        imagecolordeallocate($dest, $bgcolor);

        imagecopy($dest, $this->_handle, $ox, $oy, 0, 0, $sx, $sy);
        imagedestroy($this->_handle);
        $this->_handle = $dest;

        return $this;
    }

    /**
     * 在保持图像长宽比的情况下将图像裁减到指定大小
     *
     * crop() 在缩放图像时,可以保持图像的长宽比,从而保证图像不会拉高或压扁。
     *
     * crop() 默认情况下会按照 $width 和 $height 参数计算出最大缩放比例,
     * 保持裁减后的图像能够最大程度的充满图片。
     *
     * 例如源图的大小是 800 x 600,而指定的 $width 和 $height 是 200 和 100。
     * 那么源图会被首先缩小为 200 x 150 尺寸,然后裁减掉多余的 50 像素高度。
     *
     * 用法:
     * @code php
     * $image->crop($width, $height);
     * @endcode
     *
     * 如果希望最终生成图片始终包含完整图像内容,那么应该指定 $options 参数。
     * 该参数可用值有:
     *
     * -   fullimage: 是否保持完整图像
     * -   pos: 缩放时的对齐方式
     * -   bgcolor: 缩放时多余部分的背景色
     * -   enlarge: 是否允许放大
     * -   reduce: 是否允许缩小
     *
     * 其中 $options['pos'] 参数的可用值有:
     *
     * -   left: 左对齐
     * -   right: 右对齐
     * -   center: 中心对齐
     * -   top: 顶部对齐
     * -   bottom: 底部对齐
     * -   top-left, left-top: 左上角对齐
     * -   top-right, right-top: 右上角对齐
     * -   bottom-left, left-bottom: 左下角对齐
     * -   bottom-right, right-bottom: 右下角对齐
     *
     * 如果指定了无效的 $pos 参数,则等同于指定 center。
     *
     * $options 中的每一个选项都可以单独指定,例如在允许裁减的情况下将图像放到新图片的右下角。
     *
     * @code php
     * $image->crop($width, $height, array('pos' => 'right-bottom'));
     * @endcode
     *
     * @param int $width 新的宽度
     * @param int $height 新的高度
     * @param array $options 裁减选项
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function crop($width, $height, $options = array())
    {
        if (is_null($this->_handle)) return $this;

        $default_options = array(
            'fullimage' => false,
            'pos'       => 'center',
            'bgcolor'   => '0xfff',
            'enlarge'   => false,
            'reduce'    => true,
        );
        $options = array_merge($default_options, $options);

        // 创建目标图像
        $dest = imagecreatetruecolor($width, $height);
        // 填充背景色
        list ($r, $g, $b) = Helper_Image::hex2rgb($options['bgcolor'], '0xffffff');
        $bgcolor = imagecolorallocate($dest, $r, $g, $b);
        imagefilledrectangle($dest, 0, 0, $width, $height, $bgcolor);
        imagecolordeallocate($dest, $bgcolor);

        // 根据源图计算长宽比
        $full_w = imagesx($this->_handle);
        $full_h = imagesy($this->_handle);
        $ratio_w = doubleval($width) / doubleval($full_w);
        $ratio_h = doubleval($height) / doubleval($full_h);

        if ($options['fullimage'])
        {
            // 如果要保持完整图像,则选择最小的比率
            $ratio = $ratio_w < $ratio_h ? $ratio_w : $ratio_h;
        }
        else
        {
            // 否则选择最大的比率
            $ratio = $ratio_w > $ratio_h ? $ratio_w : $ratio_h;
        }

        if (!$options['enlarge'] && $ratio > 1) $ratio = 1;
        if (!$options['reduce'] && $ratio < 1) $ratio = 1;

        // 计算目标区域的宽高、位置
        $dst_w = $full_w * $ratio;
        $dst_h = $full_h * $ratio;

        // 根据 pos 属性来决定如何定位
        switch (strtolower($options['pos']))
        {
        case 'left':
            $dst_x = 0;
            $dst_y = ($height - $dst_h) / 2;
            break;
        case 'right':
            $dst_x = $width - $dst_w;
            $dst_y = ($height - $dst_h) / 2;
            break;
        case 'top':
            $dst_x = ($width - $dst_w) / 2;
            $dst_y = 0;
            break;
        case 'bottom':
            $dst_x = ($width - $dst_w) / 2;
            $dst_y = $height - $dst_h;
            break;
        case 'top-left':
        case 'left-top':
            $dst_x = $dst_y = 0;
            break;
        case 'top-right':
        case 'right-top':
            $dst_x = $width - $dst_w;
            $dst_y = 0;
            break;
        case 'bottom-left':
        case 'left-bottom':
            $dst_x = 0;
            $dst_y = $height - $dst_h;
            break;
        case 'bottom-right':
        case 'right-bottom':
            $dst_x = $width - $dst_w;
            $dst_y = $height - $dst_h;
            break;
        case 'center':
        default:
            $dst_x = ($width - $dst_w) / 2;
            $dst_y = ($height - $dst_h) / 2;
        }

        imagecopyresampled($dest,  $this->_handle, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $full_w, $full_h);
        imagedestroy($this->_handle);
        $this->_handle = $dest;

        return $this;
    }

    /**
     * 保存为 JPEG 文件
     *
     * @param string $filename 保存文件名
     * @param int $quality 品质参数,默认为 80
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function saveAsJpeg($filename, $quality = 80)
    {
        imagejpeg($this->_handle, $filename, $quality);
    }

    /**
     * 保存为 PNG 文件
     *
     * @param string $filename 保存文件名
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function saveAsPng($filename)
    {
        imagepng($this->_handle, $filename);
    }

    /**
     * 保存为 GIF 文件
     *
     * @param string $filename 保存文件名
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function saveAsGif($filename)
    {
        imagegif($this->_handle, $filename);
    }

    /**
     * 销毁内存中的图像
     *
     * @return Helper_ImageGD 返回 Helper_ImageGD 对象本身,实现连贯接口
     */
    function destroy()
    {
            if (!$this->_handle)
            {
            @imagedestroy($this->_handle);
            }
        $this->_handle = null;
        return $this;
    }
}

调用方法

<?php
$image = Helper_Image::createFromFile('c:a.jpg','jpg');
$image->resampled(100, 100);  //缩放到100px * 100PX
$image->saveAsJpeg('c:a_output.jpg', 100);

[!--infotagslink--]

相关文章

  • NodeJS实现阿里大鱼短信通知发送

    本文给大家介绍的是nodejs实现使用阿里大鱼短信API发送消息的方法和代码,有需要的小伙伴可以参考下。...2016-01-20
  • PHP测试成功的邮件发送案例

    mail()函数的作用:连接到邮件服务器,利用smtp协议,与该服务器交互并投邮件。注意:1、mail函数不支持esmtp协议,---即,只能直投,不能登陆2、由上条,我们只能直投至最终的收件服务器地址.而该地址,又是在PHP.ini中指定的,所...2015-10-30
  • php邮件发送的两种方式

    这篇文章研究的主要内容就是使用PHP来发送电子邮件,总结为以下两种方法:一、使用PHP内置的mail()函数<&#63;php $to = "test@163.com"; //收件人 $subject = "Test"; //主题 $message = "This is a test mail!"; //正文...2015-10-30
  • c# 实现发送邮件的功能

    这篇文章主要介绍了c# 如何实现发送邮件的功能,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-07
  • php邮件发送的两种方式

    这篇文章研究的主要内容就是使用PHP来发送电子邮件,总结为以下两种方法:一、使用PHP内置的mail()函数<&#63;php $to = "test@163.com"; //收件人 $subject = "Test"; //主题 $message = "This is a test mail!"; //正文...2015-10-30
  • PHP测试成功的邮件发送案例

    mail()函数的作用:连接到邮件服务器,利用smtp协议,与该服务器交互并投邮件。注意:1、mail函数不支持esmtp协议,---即,只能直投,不能登陆2、由上条,我们只能直投至最终的收件服务器地址.而该地址,又是在PHP.ini中指定的,所...2015-10-30
  • python实现企业微信定时发送文本消息的实例代码

    这篇文章主要介绍了python实现企业微信定时发送文本消息的实例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-25
  • node.js 基于 STMP 协议和 EWS 协议发送邮件

    这篇文章主要介绍了node.js 基于 STMP 协议和 EWS 协议发送邮件的示例,帮助大家更好的理解和使用node.js,感兴趣的朋友可以了解下...2021-02-15
  • phpMailer 发送邮件

    //原创:www.111cn.net 注明:转载说明来处www.111cn.net // 昨天听一网友说用php 里面的mail发邮件发不出去,我想一般都是发不了的,现在大多数据邮件提供商都不准那样了...2016-11-25
  • php中利用curl smtp发送邮件实例

    本文章来介绍人一下关于与我们不同的发送邮件的方法我们来利用php curl stmp来实现邮件的发送程序。 $ telnet 邮箱SMTP服务地址 25 Trying 邮箱服务IP地址......2016-11-25
  • Python基于httpx模块实现发送请求

    这篇文章主要介绍了Python基于httpx模块实现发送请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-08
  • php定时发送邮件

    <?php // 请求 PHPmailer类 文件 require_once("class.phpmailer.php"); //发送Email函数 function smtp_mail ( $sendto_email, $subject, $body, $extra_hd...2016-11-25
  • 解决PHPMailer错误SMTP Error: Could not connect to SMTP host的办法

    PHPMailer发邮件时提示SMTP Error: Could not connect to SMTP host错误是smtp服务器的问题我们一起来看看关于SMTP Error: Could not connect to SMTP host问题的解...2016-11-25
  • php天翼开放平台短信发送接口实现

    临时性需求,研究了一下天翼开发平台的东西,用来发送验证码还是不错的,但是每日限额不多,所以很鸡肋,但是保证100%到达 买的话还是蛮贵的,代码没有做任何优化处理,只是测试是...2016-11-25
  • C#实现异步发送邮件的方法

    这篇文章主要介绍了C#实现异步发送邮件的方法,涉及C#异步操作与邮件发送的技巧,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • jQuery实现订单提交页发送短信功能前端处理方法

    这篇文章主要介绍了jQuery实现订单提交页发送短信功能前端处理方法,涉及jQuery响应鼠标事件及针对页面元素的样式与字符串正则操作相关技巧,需要的朋友可以参考下...2016-07-06
  • phpmailer发送邮件 SMTP Error: Could not authenticate 错误

    今天在使用phpmailer发送邮件时居然提示SMTP Error: Could not authenticate,这个感觉是smtp设置的问题,下面我在网上找到了几种解决办法。 今天在使用phpmailer发...2016-11-25
  • Qt实现UDP多线程数据处理及发送的简单实例

    本文主要介绍了Qt实现UDP多线程数据处理及发送的简单实例,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-10-21
  • C++实现含附件的邮件发送功能

    这篇文章主要为大家详细介绍了C++实现含附件的邮件发送功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-04-25
  • phpmailer 发送邮件实例代码

    header("Content-type:text/html;charset=utf-8"); include('phpmailer/class.phpmailer.php'); include('phpmailer/class.smtp.php'); $mail = new PHPMailer();...2016-11-25