PHP生成サムネイル、ウォーターマーク

23518 ワード

<?php
class ThumbWaterImages{
    /**
     *      /   
     * classname ThumbWaterImages
     * datetime:2015-1-15
     * author:chenpz
     *
     * usuage:
     * $th=new ThumbWaterImages(array('imagePre'=>'example', 'imagePath'=>'./uploads/thumb/', 'echoType'=>'file'));
     * $th->setThumb($srcImage, 384, 300, 'prorate');
     */
     
    private $imagepre;				//       
    private $imagepath;				//       
    private $srcImage='';			//    
    private $newImageName;			//     
    private $imageType;				//    
    private $echotype;				//      ,link--        ;file--     
    private $im='';					//    
    private $originName='';			//    
    private $srcW='';				//   
    private $srcH='';				//   
    private $errorNum=0;			//   
    private $errorMess='';			//        
    
 	
 	/**
 	*	   
 	*	@access public
 	*	@param	array
 	*	@return void
 	*/
    public function __construct($options = array()){
        $allowOption = array('imagepre','imagepath','echotype');
        foreach($options as $key=>$val){
            $key = strtolower($key);
            //      
            if(!in_array($key, $allowOption)){
                $this->errorNum = -3;
                $this->errorMess = $this->getError();
                continue;
            }
            $this->$key = $val;
        }
    }
    
    /**
     * 
     *        、           
     *   GD          
     *        、       、       
     *
     * @access public
     * @param string $srcImage
     * @param int $toW
     * @param int $toH
     * @param string $method	
     *	prorate      /distortion      /cut         /backFill      
     * @param string $echotype
     */
    public function setThumb($srcImage = '', $toW = 0, $toH = 0, $method = 'distortion'){
        $this->srcImage = $srcImage;
        $imageName = explode('/', $this->srcImage);
        $this->originName = $imageName[2];
           //         
        if(empty($srcImage) || filetype($srcImage) != 'file'){
            $this->errorNum = 4;
            $this->errorMess = $this->getError();
            return false;
        }
        //        
        if ($this->echotype == 'file'){
            if(!$this->checkImagePath()){
                $this->errorMess = $this->getError();
                return false;
            }
        }
        $info = '';
        $data = getimagesize($this->srcImage, $info);//      
        $this->srcW = $data[0];// 
        $this->srcH = $data[1];// 
         //  GD 
        if(!$this->checkGD($data[2])){
            $this->errorMess = $this->getError();
            return false;
        }
        $this->setImageName();//       
        $toFile = $this->imagepath.$this->newImageName;//       
        $return = $this->createImageMethod($method, $toFile, $toW, $toH);
		return $return;
    }
    
    /**
     * 
     *           
     * prorate      
     * distortion      
     * cut         
     * backFill      
     * @param string $method
     * @param string $toFile
     * @param int $toW
     * @param int $toH
     */
    private function createImageMethod($method, $toFile, $toW, $toH){
        switch ($method){
              case 'prorate':
                  $return = $this->prorate($toFile, $toW, $toH);
                  break;
              case 'cut':
                  $return = $this->cut($toFile, $toW, $toH);
                  break;
              case 'backFill':
                  $return = $this->backFill($toFile, $toW, $toH);
                  break;
              default:
                  $return = $this->distortion($toFile, $toW, $toH);
           }
           return $return;
    }
    //       
    function distortion($toFile='', $toW=0, $toH=0){
        $cImg=$this->creatImage($this->im, $toW, $toH, 0, 0, 0, 0, $this->srcW, $this->srcH);
        return $this->echoImage($cImg, $toFile);
        imagedestroy($cImg);
    }
    
    //          
    function prorate($toFile, $toW, $toH){
        $toWH = $toW / $toH;
        $srcWH = $this->srcW / $this->srcH;
        if($toWH <= $srcWH){
            $ftoW = $toW;
            $ftoH = $ftoW * ($this->srcH / $this->srcW);
        }else{
              $ftoH = $toH;
              $ftoW = $ftoH * ($this->srcW / $this->srcH);
        }
        if($this->srcW > $toW || $this->srcH > $toH){
            $cImg = $this->creatImage($this->im, $ftoW, $ftoH, 0, 0, 0, 0, $this->srcW, $this->srcH);
            return $this->echoImage($cImg, $toFile);
            imagedestroy($cImg);
        }else{
            $cImg = $this->creatImage($this->im, $this->srcW, $this->srcH, 0, 0, 0, 0, $this->srcW, $this->srcH);
            return $this->echoImage($cImg, $toFile);
            imagedestroy($cImg);
        }
    }
    
    //          
    private function cut($toFile, $toW, $toH){
          $toWH = $toW/$toH;
          $srcWH = $this->srcW / $this->srcH;
          if($toWH <= $srcWH){
               $ctoH = $toH;
               $ctoW = $ctoH * ($this->srcW / $this->srcH);
          }else{
              $ctoW = $toW;
              $ctoH = $ctoW * ($this->srcH / $this->srcW);
          } 
        $allImg = $this->creatImage($this->im, $ctoW, $ctoH, 0, 0, 0, 0, $this->srcW, $this->srcH);
        $cImg = $this->creatImage($allImg, $toW, $toH, 0, 0, ($ctoW-$toW) / 2, ($ctoH-$toH) / 2, $toW, $toH);
        return $this->echoImage($cImg, $toFile);
        imagedestroy($cImg);
        imagedestroy($allImg);
    }
 
    //         
    private function backFill($toFile, $toW, $toH, $bk1=255, $bk2=255, $bk3=255){
        $toWH = $toW / $toH;
        $srcWH = $this->srcW / $this->srcH;
        if($toWH <= $srcWH){
            $ftoW = $toW;
            $ftoH = $ftoW * ($this->srcH / $this->srcW);
        }else{
              $ftoH = $toH;
              $ftoW = $ftoH*($this->srcW / $this->srcH);
        }
        if(function_exists("imagecreatetruecolor")){
            @$cImg = imagecreatetruecolor($toW,$toH);
            if(!$cImg){
                $cImg = imagecreate($toW,$toH);
            }
        }else{
            $cImg = imagecreate($toW,$toH);
        }
        $backcolor = imagecolorallocate($cImg, $bk1, $bk2, $bk3);        //       
        imagefilledrectangle($cImg,0,0,$toW,$toH,$backcolor);
        if($this->srcW > $toW || $this->srcH > $toH){
            $proImg = $this->creatImage($this->im,$ftoW,$ftoH,0,0,0,0,$this->srcW,$this->srcH);
            if($ftoW < $toW){
                 imagecopy($cImg, $proImg, ($toW - $ftoW) / 2, 0, 0, 0, $ftoW, $ftoH);
            }else if($ftoH < $toH){
                 imagecopy($cImg, $proImg, 0, ($toH-$ftoH) / 2, 0, 0, $ftoW, $ftoH);
            }else{
                 imagecopy($cImg, $proImg, 0, 0, 0, 0, $ftoW, $ftoH);
            }
        }else{
             imagecopymerge($cImg, $this->im, ($toW - $ftoW) / 2,($toH - $ftoH) / 2, 0, 0, $ftoW, $ftoH, 100);
        }
        return $this->echoImage($cImg, $toFile);
        imagedestroy($cImg);
    }
    //    
    private function creatImage($img, $creatW, $creatH, $dstX, $dstY, $srcX, $srcY, $srcImgW, $srcImgH){
        if(function_exists("imagecreatetruecolor")){
            @$creatImg = imagecreatetruecolor($creatW, $creatH);
            if($creatImg){
                imagecopyresampled($creatImg, $img, $dstX, $dstY, $srcX, $srcY, $creatW, $creatH, $srcImgW, $srcImgH);
            }else{
                $creatImg=imagecreate($creatW,$creatH);
                imagecopyresized($creatImg, $img, $dstX, $dstY, $srcX, $srcY, $creatW, $creatH, $srcImgW, $srcImgH);
            }
         }else{
            $creatImg=imagecreate($creatW, $creatH);
            imagecopyresized($creatImg, $img, $dstX, $dstY, $srcX, $srcY, $creatW, $creatH, $srcImgW, $srcImgH);
         }
         return $creatImg;
    }
    
    //    ,link---   ,     。file--     
    function echoImage($img, $toFile){
        switch($this->echotype){
            case 'link':
                if(function_exists('imagejpeg')) 
                    return imagejpeg($img);
                else 
                    return imagepng($img);
                break;
            case 'file':
                if(function_exists('imagejpeg')) 
                    return imagejpeg($img,$toFile);
                else 
                    return imagepng($img,$toFile);
                break;
        }
    }
    /**
     * 
     *         
     * @access private
     * @return string
     */
    private function setRandName(){
        $fileName = date("YmdHis").rand(100,999);
        return $fileName.'.'.$this->imageType;
    }
    private function setImageName(){
        if ($this->imagepre != ''){
            $this->newImageName = $this->imagepre.'_'.$this->setRandName();
        }else {
            $this->newImageName = $this->setRandName();
        }
    }
    /**
     * 
     *           
     * @access private
     * @return bool
     */
    private function checkImagePath(){
        if(empty($this->imagepath)) {
            $this->errorNum = -2;
            return false;
        }

        if(!file_exists($this->imagepath) || !is_writable($this->imagepath)){
            if(!@mkdir($this->imagepath, 0755,true)){
                $this->errorNum = -1;
                return false;
            }
        }
        return true;
    }
    private function checkGD($imageType){
        switch ($imageType){
             case 1:
               if(!function_exists("imagecreatefromgif")){
                       $this->errorNum = 1;
                       return false;
               }
               $this->imageType = 'gif';
               $this->im = imagecreatefromgif($this->srcImage);
               break;
             case 2:
               if(!function_exists("imagecreatefromjpeg")){
                     $this->errorNum = 2;
                     return false;
                }
                $this->imageType = 'jpg';
                $this->im = imagecreatefromjpeg($this->srcImage);    
                break;
             case 3:
                if(!function_exists("imagecreatefrompng")){
                      $this->errorNum = 3;
                      return false;
                 }
                 $this->imageType = 'png';
                 $this->im = imagecreatefrompng($this->srcImage);    
                 break;
              default:
                 $this->errorNum = 0;
                 return false;
          }
          return true;
    }
    /**
     * 
     *                
     * @access public
     * @return string
     */
    public function getNewImageName(){
        return $this->newImageName;
    }

    /**
     * 
     *         
     * @access private
     * @return string
     */
    private function getError(){
        $str='     <font color="red">'.$this->originName.'</font>   :';

        switch($this->errorNum){
            case 4: $str .= '           '; 
                break;
            case 3: $str .= '  GD     png     ,          !'; 
                break;
            case 2: $str .= '  GD     jpeg     ,          !';
                break;
            case 1: $str .= '  GD     GIF     ,   Jpeg PNG  !';
                break;
            case -1: $str .= '           ,          ';
                break;
            case -2: $str .= '          ';
                break;
            case -3: $str .= '       ';
                break;
            default: $str .= '    ';
        }

        return $str.'<br>';
    }
    public function getErrorMsg() {
        return $this->errorMess;
    }
    
    
    /* 
		*   :PHP     (         ) 
		*   : 
		*      $groundImage        ,         ,    GIF,JPG,PNG  ; 
		*      $waterPos            , 10   ,0     ; 
		*                        1     ,2     ,3     ; 
		*                        4     ,5     ,6     ; 
		*                        7     ,8     ,9     ; 
		*      $waterImage            ,        ,    GIF,JPG,PNG  ; 
		*      $waterText            ,         ,  ASCII ,     ; 
		*      $textFont            ,  1、2、3、4 5,   5; 
		*      $textColor            ,         ,   #FF0000(  ); 
		* 
		*   :Support GD 2.0,Support FreeType、GIF Read、GIF Create、JPG 、PNG 
		*      $waterImage   $waterText         ,       ,     $waterImage。 
		*       $waterImage   ,  $waterString、$stringFont、$stringColor    。 
		*                   $groundImage   。 
		*/ 
		public function imageWaterMark($groundImage,$waterPos=0,$waterImage="",$waterText="",$textFont=5,$textColor="#FF0000") 
		{ 
		    $isWaterImage = FALSE; 
		    $formatMsg = "         ,              GIF、JPG、PNG  。"; 

		    //       
		    if(!empty($waterImage) && file_exists($waterImage)) 
		    { 
		        $isWaterImage = TRUE; 
		        $water_info = getimagesize($waterImage); 
		        $water_w    = $water_info[0];//         
		        $water_h    = $water_info[1];//         

		        switch($water_info[2])//          
		        { 
		            case 1:$water_im = imagecreatefromgif($waterImage);break; 
		            case 2:$water_im = imagecreatefromjpeg($waterImage);break; 
		            case 3:$water_im = imagecreatefrompng($waterImage);break; 
		            default: return false;//die($formatMsg); 
		        } 
		    } 

		    //       
		    if(!empty($groundImage) && file_exists($groundImage)) 
		    { 
		        $ground_info = getimagesize($groundImage); 
		        $ground_w    = $ground_info[0];//         
		        $ground_h    = $ground_info[1];//         

		        switch($ground_info[2])//          
		        { 
		            case 1:$ground_im = imagecreatefromgif($groundImage);break; 
		            case 2:$ground_im = imagecreatefromjpeg($groundImage);break; 
		            case 3:$ground_im = imagecreatefrompng($groundImage);break; 
		            default:return false;//die($formatMsg); 
		        } 
		    } 
		    else 
		    { 
		        return false;
				//die("           !"); 
		    } 

		    //     
		    if($isWaterImage)//     
		    { 
		        $w = $water_w; 
		        $h = $water_h; 
		        $label = "   "; 
		    } 
		    else//     
		    { 
		        $temp = imagettfbbox(ceil($textFont*2.5),0,"./fonts/Eras_Bold_ITC.otf",$waterText);//     TrueType          
		        $w = $temp[2] - $temp[6]; 
		        $h = $temp[3] - $temp[7]; 
		        unset($temp); 
		        $label = "    "; 
		    } 
		    if( ($ground_w<$w) || ($ground_h<$h) ) 
		    { 
		        //echo "                 ".$label."  ,      !"; 
		        return; 
		    } 
		    switch($waterPos) 
		    { 
		        case 0://   
		            $posX = rand(0,($ground_w - $w)); 
		            $posY = rand(0,($ground_h - $h)); 
		            break; 
		        case 1://1      
		            $posX = 0; 
		            $posY = 0; 
		            break; 
		        case 2://2      
		            $posX = ($ground_w - $w) / 2; 
		            $posY = 0; 
		            break; 
		        case 3://3      
		            $posX = $ground_w - $w; 
		            $posY = 0; 
		            break; 
		        case 4://4      
		            $posX = 0; 
		            $posY = ($ground_h - $h) / 2; 
		            break; 
		        case 5://5      
		            $posX = ($ground_w - $w) / 2; 
		            $posY = ($ground_h - $h) / 2; 
		            break; 
		        case 6://6      
		            $posX = $ground_w - $w; 
		            $posY = ($ground_h - $h) / 2; 
		            break; 
		        case 7://7      
		            $posX = 0; 
		            $posY = $ground_h - $h; 
		            break; 
		        case 8://8      
		            $posX = ($ground_w - $w) / 2; 
		            $posY = $ground_h - $h; 
		            break; 
		        case 9://9      
		            $posX = $ground_w - $w; 
		            $posY = $ground_h - $h; 
		            break; 
		        default://   
		            //$posX = rand(0,($ground_w - $w)); 
		            //$posY = rand(0,($ground_h - $h)); 
					$posX = 5;
					$posY = 55;
		            break;     
		    } 

		    //          
		    imagealphablending($ground_im, true); 

		    if($isWaterImage)//     
		    { 
		        imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//                  
		    } 
		    else//     
		    { 
		        if( !empty($textColor) && (strlen($textColor)==7) ) 
		        { 
		            $R = hexdec(substr($textColor,1,2)); 
		            $G = hexdec(substr($textColor,3,2)); 
		            $B = hexdec(substr($textColor,5)); 
		        } 
		        else 
		        { 
		            return false;
					//die("           !"); 
		        } 
		        imagestring ( $ground_im, $textFont, $posX, $posY, $waterText, imagecolorallocate($ground_im, $R, $G, $B));         
		    } 

		    //         
		    @unlink($groundImage); 
		    switch($ground_info[2])//          
		    { 
		        case 1:imagegif($ground_im,$groundImage);break; 
		        case 2:imagejpeg($ground_im,$groundImage);break; 
		        case 3:imagepng($ground_im,$groundImage);break; 
		        default:return false;//die($errorMsg); 
		    } 

		    //     
		    if(isset($water_info)) unset($water_info); 
		    if(isset($water_im)) imagedestroy($water_im); 
		    unset($ground_info); 
		    imagedestroy($ground_im); 
		} 



	/**
	 *         
	 *
	 * @param $filename           
	 * @param $w                  
	 * @param $h                 
	 * @param $override              
	 * @param $background        ,                    ,       
	 * @param $color               
	 */
	public function RatioAdjuct($filename = '', $w = 440, $h = 300, $override = null, $background = null, $color = '0xFFFFFF') {
		list( $imgWidth, $imgHeight ) = getImageSize ( $filename );
		
		$ratioX = $imgWidth / $w;
		$ratioY = $imgHeight / $h;
		
		if ($ratioX > $ratioY || $ratioX == $ratioY) {
			$dst_w = $w;
			$dst_h = ceil ( $imgHeight / $ratioX );
		} else if ($ratioY > $ratioX) {
			$dst_h = $h;
			$dst_w = ceil ( $imgWidth / $ratioY );
		}
		
		//      
		switch (strtolower ( strrchr ( $filename, '.' ) )) {
			case '.jpg' :
			case '.jpeg' :
				$im = imageCreateFromJpeg ( $filename );
				break;
			case '.gif' :
				$im = imageCreateFromGif ( $filename );
				break;
			
			case '.png' :
				$im = imageCreateFromPng ( $filename );
		}
		
		//      
		if (null !== $background) {
			//               
			$dec = hexdec ( $color );
			$red = 0xFF & ($dec >> 0x10);
			$green = 0xFF & ($dec >> 0x8);
			$blue = 0xFF & $dec;
			
			//       
			$dst_pos = array ('d_x' => 0, 'd_y' => 0 );
			($dst_w == $w) ? ($dst_pos ['d_y'] = (($h - $dst_h) / 2)) : ($dst_pos ['d_x'] = (($w - $dst_w) / 2));
			
			$imBox = imageCreateTrueColor ( $w, $h );
			$color_bg = imageColorAllocate ( $imBox, $red, $green, $blue );
			imageFill ( $imBox, 0, 0, $color_bg );
			imageCopyResized ( $imBox, $im, $dst_pos ['d_x'], $dst_pos ['d_y'], 0, 0, $dst_w, $dst_h, $imgWidth, $imgHeight );
		} else {
			$imBox = imageCreateTrueColor ( $dst_w, $dst_h );
			imageCopyResized ( $imBox, $im, 0, 0, 0, 0, $dst_w, $dst_h, $imgWidth, $imgHeight );
		}
		
		//      
		if (null === $override)
			$filename = str_replace ( strrchr ( $filename, '.' ), '', $filename ) . '_thumb.png';
		
		return imagejpeg ( $imBox, $filename ) ? $filename : false;
	}
}


$th=new ThumbImages(array('imagePre'=>'xxs', 'imagePath'=>'./uploads/thumb/', 'echoType'=>'file'));
$th->imageWaterMark('1034035813_x.jpg', 6, 'sy_small.png');

$th->setThumb('1034035813_x.jpg', 400, 400, 'cut');