PHP智能把图片生成缩略图类

 更新时间:2016年11月25日 16:56  点击:1425
一个PHP智能把图片生成缩略图类,可自动根据你图片的大小生成等比例的图片哦,有需要的朋友可参考参考。
 代码如下 复制代码
< ?php
  
 /***************************************  *作者:落梦天蝎(beluckly)
 *完成时间:2006-12-18
 *类名:CreatMiniature
 *功能:生成多种类型的缩略图
 *基本参数:$srcFile,$echoType
 *方法用到的参数:
                 $toFile,生成的文件
                 $toW,生成的宽
                 $toH,生成的高
                 $bk1,背景颜色参数 以255为最高
                 $bk2,背景颜色参数
                 $bk3,背景颜色参数
  
 *例子:
  
     include("thumb.php");
     $cm=new CreatMiniature();
     $cm->SetVar("1.jpg","file");
     $cm->Distortion("dis_bei.jpg",150,200);
     $cm->Prorate("pro_bei.jpg",150,200);
     $cm->Cut("cut_bei.jpg",150,200);
      $cm->BackFill("fill_bei.jpg",150,200);
  
 ***************************************/
  
 class CreatMiniature
 {
     //公共变量
     var $srcFile="";        //原图
     var $echoType;            //输出图片类型,link--不保存为文件;file--保存为文件
     var $im="";                //临时变量
     var $srcW="";            //原图宽
     var $srcH="";            //原图高
  
     //设置变量及初始化
     function SetVar($srcFile,$echoType)
     {
         $this->srcFile=$srcFile;
         $this->echoType=$echoType;
  
         $info = "";
         $data = GetImageSize($this->srcFile,$info);
         switch ($data[2])          {
          case 1:
            if(!function_exists("imagecreatefromgif")){
             echo "你的GD库不能使用GIF格式的图片,请使用Jpeg或PNG格式!<a href='javascript:go(-1);'>返回</a>";
             exit();
            }
            $this->im = ImageCreateFromGIF($this->srcFile);
            break;
         case 2:
           if(!function_exists("imagecreatefromjpeg")){
            echo "你的GD库不能使用jpeg格式的图片,请使用其它格式的图片!<a href='javascript:go(-1);'>返回</a>";
            exit();
           }
           $this->im = ImageCreateFromJpeg($this->srcFile);    
           break;
         case 3:
           $this->im = ImageCreateFromPNG($this->srcFile);    
           break;
       }
       $this->srcW=ImageSX($this->im);
       $this->srcH=ImageSY($this->im); 
     }
     
     //生成扭曲型缩图
     function Distortion($toFile,$toW,$toH)
     {
         $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);
         }
     }
     
     //生成最小裁剪后的缩图
     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);
     }
  
     //生成背景填充的缩图
     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)
              {
                  ImageCopyMerge($cImg,$proImg,($toW-$ftoW)/2,0,0,0,$ftoW,$ftoH,100);
              }
              else if($ftoH<$toH)
              {
                  ImageCopyMerge($cImg,$proImg,0,($toH-$ftoH)/2,0,0,$ftoW,$ftoH,100);
              }
              */
             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);
     }
     
  
     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,$to_File)
     {
         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,$to_File);
                 else return ImagePNG($img,$to_File);
                 break;
         }
     }
  
 }
 ?>
ImageCode函数通过GIFEncoder类实现的GIF动画的PHP源代码,有兴趣的朋友可以研究一下。
 代码如下 复制代码

<?php
/**
 * 调用示例
 * */
session_start();
$randCode = '';
$chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ23456789';
for ( $i = 0; $i < 4; $i++ )
{
 $randCode .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
$_SESSION['code'] = strtoupper($randCode);   // 记录session
ImageCode($randCode, 60);    // 显示GIF动画

/**
 * ImageCode 生成GIF图片验证
 * @param $string 字符串
 * @param $width 宽度
 * @param $height 高度
 * */
function ImageCode($string = '', $width = 75, $height = 25)
{
 $authstr = $string ? $string : ((time() % 2 == 0) ? mt_rand(1000, 9999) : mt_rand(10000, 99999));
 
 $board_width = $width;
 $board_height = $height;
 // 生成一个32帧的GIF动画
 for($i = 0; $i < 32; $i++)
 {
  ob_start();
     $image = imagecreate($board_width, $board_height);
     imagecolorallocate($image, 0,0,0);
     // 设定文字颜色数组
   $colorList[] = ImageColorAllocate($image, 15,73,210);
   $colorList[] = ImageColorAllocate($image, 0,64,0);
   $colorList[] = ImageColorAllocate($image, 0,0,64);
   $colorList[] = ImageColorAllocate($image, 0,128,128);
   $colorList[] = ImageColorAllocate($image, 27,52,47);
   $colorList[] = ImageColorAllocate($image, 51,0,102);
   $colorList[] = ImageColorAllocate($image, 0,0,145);
   $colorList[] = ImageColorAllocate($image, 0,0,113);
   $colorList[] = ImageColorAllocate($image, 0,51,51);
   $colorList[] = ImageColorAllocate($image, 158,180,35);
   $colorList[] = ImageColorAllocate($image, 59,59,59);
   $colorList[] = ImageColorAllocate($image, 0,0,0);
   $colorList[] = ImageColorAllocate($image, 1,128,180);
   $colorList[] = ImageColorAllocate($image, 0,153,51);
   $colorList[] = ImageColorAllocate($image, 60,131,1);
   $colorList[] = ImageColorAllocate($image, 0,0,0);
   $fontcolor = ImageColorAllocate($image, 0,0,0);
   $gray = ImageColorAllocate($image, 245,245,245);
   
     $color = imagecolorallocate($image, 255,255,255);
     $color2 = imagecolorallocate($image, 255,0,0);
    
     imagefill($image, 0, 0, $gray);
    
     $space = 15;  // 字符间距
     if($i > 0)   // 屏蔽第一帧
     {
      for ($k = 0; $k < strlen($authstr); $k++)
      {
    $colorRandom = mt_rand(0,sizeof($colorList)-1);
    $float_top = rand(0,4);
    $float_left = rand(0,3);
    imagestring($image, 6, $space * $k, $top + $float_top, substr($authstr, $k, 1), $colorList[$colorRandom]);
   }
     }
    
  for ($k = 0; $k < 20; $k++)
  {
   $colorRandom = mt_rand(0,sizeof($colorList)-1);
    imagesetpixel($image, rand()%70 , rand()%15 , $colorList[$colorRandom]);
 
  }
  // 添加干扰线
  for($k = 0; $k < 3; $k++)
  {
   $colorRandom = mt_rand(0, sizeof($colorList)-1);
   // $todrawline = rand(0,1);
   $todrawline = 1;
   if($todrawline)
   {
    imageline($image, mt_rand(0, $board_width), mt_rand(0,$board_height), mt_rand(0,$board_width), mt_rand(0,$board_height), $colorList[$colorRandom]);
   }
   else
   {
    $w = mt_rand(0,$board_width);
    $h = mt_rand(0,$board_width);
    imagearc($image, $board_width - floor($w / 2) , floor($h / 2), $w, $h,  rand(90,180), rand(180,270), $colorList[$colorRandom]);
   }
  }
     imagegif($image);
     imagedestroy($image);
     $imagedata[] = ob_get_contents();
     ob_clean(); 
     ++$i; 
 }
 
 $gif = new GIFEncoder($imagedata); 
 Header ('Content-type:image/gif'); 
 echo $gif->GetAnimation(); 
}


/**
 * GIFEncoder类
 * */
Class GIFEncoder
{
    var $GIF = "GIF89a";                /* GIF header 6 bytes        */ 
    var $VER = "GIFEncoder V2.06";        /* Encoder version             */ 

    var $BUF = Array ( ); 
    var $LOP =  0; 
    var $DIS =  2; 
    var $COL = -1; 
    var $IMG = -1; 

    var $ERR = Array ( 
        'ERR00' =>"Does not supported function for only one image!", 
        'ERR01' =>"Source is not a GIF image!", 
        'ERR02' =>"Unintelligible flag ", 
        'ERR03' =>"Could not make animation from animated GIF source", 
    ); 
   
    function GIFEncoder ($GIF_src, $GIF_dly = 100, $GIF_lop = 0, $GIF_dis = 0,  $GIF_red = 0, $GIF_grn = 0, $GIF_blu = 0, $GIF_mod = 'bin' )
    { 
        if (!is_array($GIF_src) && !is_array($GIF_tim))
        { 
            printf ( "%s: %s", $this->VER, $this->ERR['ERR00']); 
            exit( 0 );
        } 
        $this->LOP = ($GIF_lop > -1) ? $GIF_lop : 0; 
        $this->DIS = ($GIF_dis > -1) ? (( $GIF_dis < 3 ) ? $GIF_dis : 3) : 2; 
        $this->COL = ($GIF_red > -1 && $GIF_grn > -1 && $GIF_blu > -1) ? ($GIF_red | ($GIF_grn << 8) | ($GIF_blu << 16)) : -1; 

        for ($i = 0, $src_count = count($GIF_src); $i < $src_count; $i++ )
        {
            if (strToLower( $GIF_mod ) == "url")
            { 
             $this->BUF[] = fread (fopen($GIF_src [$i], "rb"), filesize ($GIF_src [$i])); 
            } 
            elseif(strToLower($GIF_mod) == "bin")
            { 
                $this->BUF [ ] = $GIF_src [ $i ]; 
            } 
            else
            { 
                printf("%s: %s ( %s )!", $this->VER, $this->ERR [ 'ERR02' ], $GIF_mod); 
                exit(0); 
            } 
            if (substr($this->BUF[$i], 0, 6) != "GIF87a" && substr($this->BUF [$i], 0, 6) != "GIF89a")
            { 
                printf( "%s: %d %s", $this->VER, $i, $this->ERR ['ERR01']); 
                exit(0); 
            } 
            for ($j = (13 + 3 * (2 << (ord($this->BUF[$i]{10}) & 0x07 ))), $k = TRUE; $k; $j++)
            { 
                switch ($this->BUF [$i]{$j})
                { 
                    case "!": 
                        if ((substr($this->BUF[$i], ($j + 3), 8)) == "NETSCAPE")
                        { 
                                printf( "%s: %s ( %s source )!", $this->VER, $this->ERR ['ERR03'], ($i + 1)); 
                                exit( 0 ); 
                        } 
                        break; 
                    case ";": 
                        $k = FALSE; 
                        break; 
                } 
            } 
        } 
        GIFEncoder::GIFAddHeader(); 
        for($i = 0, $count_buf = count($this->BUF); $i < $count_buf; $i++)
        { 
         GIFEncoder::GIFAddFrames($i, $GIF_dly[$i]); 
        } 
        GIFEncoder::GIFAddFooter(); 
    } 
   
    function GIFAddHeader ( )
    { 
  $cmap = 0; 
  
  if (ord($this->BUF[0]{10}) & 0x80 )
  { 
   $cmap = 3 * ( 2 << ( ord ( $this->BUF [ 0 ]{10} ) & 0x07 )); 
   
   $this->GIF .= substr ( $this->BUF [ 0 ], 6, 7); 
   $this->GIF .= substr ( $this->BUF [ 0 ], 13, $cmap); 
   $this->GIF .= "!37713NETSCAPE2.031" . GIFEncoder::GIFWord ( $this->LOP ) . ""; 
  } 
    } 
   
    function GIFAddFrames ( $i, $d )
    { 

        $Locals_str = 13 + 3 * (2 <<(ord($this->BUF[$i]{10}) & 0x07)); 

        $Locals_end = strlen($this->BUF[$i]) - $Locals_str - 1; 
        $Locals_tmp = substr ($this->BUF[$i], $Locals_str, $Locals_end); 

        $Global_len = 2 << (ord( $this->BUF [0]{10} ) & 0x07 ); 
        $Locals_len = 2 << (ord( $this->BUF[$i]{10}) & 0x07); 

        $Global_rgb = substr($this->BUF[0], 13, 3 * (2 << ( ord ( $this->BUF[0]{10} ) & 0x07))); 
        $Locals_rgb = substr ( $this->BUF[$i], 13, 3 * (2 << ( ord ( $this->BUF[$i]{10} ) & 0x07))); 

        $Locals_ext = "!xF9x04" . chr(($this->DIS << 2) + 0) . chr(($d >> 0) & 0xFF) . chr(($d >> 8) & 0xFF) . "x0x0"; 

        if ( $this->COL > -1 && ord($this->BUF[$i]{10}) & 0x80)
        { 
            for($j = 0; $j < (2 << (ord( $this->BUF[$i]{10}) & 0x07)); $j++ )
            { 
                if(ord ($Locals_rgb{3 * $j + 0}) == ($this->COL >>  0) & 0xFF && ord ( $Locals_rgb { 3 * $j + 1 } ) == ( $this->COL >>  8 ) & 0xFF && ord ( $Locals_rgb { 3 * $j + 2 } ) == ( $this->COL >> 16 ) & 0xFF )
                { 
                    $Locals_ext = "!xF9x04" . chr(($this->DIS << 2) + 1) . chr (( $d >> 0) & 0xFF) . chr (( $d >> 8) & 0xFF) . chr ($j) . "x0"; 
                    break; 
                } 
            } 
        } 
        switch ( $Locals_tmp { 0 } )
        { 
            case "!": 
                $Locals_img = substr($Locals_tmp, 8, 10); 
                $Locals_tmp = substr($Locals_tmp, 18, strlen ($Locals_tmp) - 18); 
                break; 
            case ",": 
                $Locals_img = substr($Locals_tmp, 0, 10); 
                $Locals_tmp = substr($Locals_tmp, 10, strlen($Locals_tmp) - 10); 
                break; 
        } 
        if ( ord ( $this->BUF[$i]{10} ) & 0x80 && $this->IMG > -1 )
        { 
            if ( $Global_len == $Locals_len )
            { 
    if ( GIFEncoder::GIFBlockCompare ( $Global_rgb, $Locals_rgb, $Global_len ) )
    { 
     $this->GIF .= ( $Locals_ext . $Locals_img . $Locals_tmp ); 
    } 
    else
    { 
     $byte  = ord ( $Locals_img{9}); 
     $byte |= 0x80; 
     $byte &= 0xF8; 
     $byte |= ( ord ( $this->BUF [ 0 ]{10}) & 0x07); 
     $Locals_img{9} = chr($byte); 
     $this->GIF .= ($Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp); 
    } 
            } 
            else
            { 
                $byte  = ord($Locals_img{9}); 
                $byte |= 0x80; 
                $byte &= 0xF8; 
                $byte |= (ord($this->BUF[$i]{10}) & 0x07); 
                $Locals_img {9} = chr($byte); 
                $this->GIF .= ($Locals_ext . $Locals_img . $Locals_rgb . $Locals_tmp); 
            } 
        } 
        else
        { 
            $this->GIF .= ( $Locals_ext . $Locals_img . $Locals_tmp ); 
        } 
        $this->IMG  = 1; 
    } 
   
    function GIFAddFooter ( ) { 
        $this->GIF .= ";"; 
    } 
   
    function GIFBlockCompare ( $GlobalBlock, $LocalBlock, $Len )
    { 
        for ( $i = 0; $i < $Len; $i++ )
        { 
            if($GlobalBlock { 3 * $i + 0 } != $LocalBlock { 3 * $i + 0 } || $GlobalBlock { 3 * $i + 1 } != $LocalBlock { 3 * $i + 1 } || $GlobalBlock { 3 * $i + 2 } != $LocalBlock{3 * $i + 2})
            { 
                return ( 0 ); 
            } 
        } 
        return ( 1 ); 
    } 
   
    function GIFWord ( $int )
    { 
       return ( chr ( $int & 0xFF ) . chr ( ( $int >> 8 ) & 0xFF ) ); 
    } 
   
    function GetAnimation ( )
    { 
        return ($this->GIF); 
    } 
}

在php中生成缩略图是程序开发中常用的,下面我找了几个不错的php生成缩略图的实现程序,有需要的朋友可使用,本人亲测绝对好用哦。

 

创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。

 代码如下 复制代码

 
/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
    $ext = explode(".", $filename);
    $ext = $ext[count($ext)-1];

    if($ext == "jpg" || $ext == "jpeg")
        $im = imagecreatefromjpeg($tmpname);
    elseif($ext == "png")
        $im = imagecreatefrompng($tmpname);
    elseif($ext == "gif")
        $im = imagecreatefromgif($tmpname);

    $x = imagesx($im);
    $y = imagesy($im);

    if($x <= $xmax && $y <= $ymax)
        return $im;

    if($x >= $y) {
        $newx = $xmax;
        $newy = $newx * $y / $x;
    }
    else {
        $newy = $ymax;
        $newx = $x / $y * $newy;
    }

    $im2 = imagecreatetruecolor($newx, $newy);
    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
    return $im2;
}

例2

 代码如下 复制代码

function creat_thumbnail($img,$w,$h,$path)
{
 $org_info = getimagesize($img); //获得图像大小且是通过post传递过来的
 //var_dump($org_info);
 //Array ( [0] => 1024 [1] => 768 [2] => 3 [3] => width="1024" height="768" [bits] => 8 [mime] => image/png )
 $orig_x = $org_info[0]; //图像宽度
 $orig_y = $org_info[1]; //图像高度
 $orig_type = $org_info[2]; //图片类别即后缀 1 = GIF,2 = JPG,3 = PNG,

 //是真彩色图像
 if (function_exists("imagecreatetruecolor"))
 {
  switch($orig_type)
  {
   //从给定的gif文件名中取得的图像
   case 1  : $thumb_type = ".gif"; $_creatImage = "imagegif"; $_function = "imagecreatefromgif";
   break;
   //从给定的jpeg,jpg文件名中取得的图像
   case 2  : $thumb_type = ".jpg"; $_creatImage = "imagejpeg"; $_function = "imagecreatefromjpeg";
   break;
   //从给定的png文件名中取得的图像
   case 3  : $thumb_type = ".png"; $_creatImage = "imagepng"; $_function = "imagecreatefrompng";
   break;
  }
 }
 //如果从给定的文件名可取得的图像
 if(function_exists($_function))
 {
  $orig_image = $_function($img); //从给定的$img文件名中取得的图像
 }
 if (($orig_x / $orig_y) >= (4 / 3)) //如果宽/高 >= 4/3
 {
  $y = round($orig_y / ($orig_x / $w)); //对浮点数进行四舍五入
  $x = $w;
 }
 else //即 高/宽 >= 4/3
 {
  $x = round($orig_x / ($orig_y / $h));
  $y = $h;
 }
 $sm_image = imagecreatetruecolor($x, $y); //创建真彩色图片
 //重采样拷贝部分图像并调整大小
 Imagecopyresampled($sm_image, $orig_image, 0, 0, 0, 0, $x, $y, $orig_x, $orig_y);
 //imageJPEG($sm_image, '', 80); //在浏览器输出图像
 $tnpath = $path."/"."s_".date('YmdHis').$thumb_type; //缩略图的路径
 $thumbnail = @$_creatImage($sm_image, $tnpath, 80); //生成图片,成功返回true(或1)
 imagedestroy ($sm_image); //销毁图像
 if($thumbnail==true)
 {
  return $tnpath;
 }
}

生成缩略图是当我们要上传图片时如果图片较大我们需要生成一张指定大小的小图以在列表页面显示,这样可节省资源也是现在常用的做法,下面我来分享一个php生成缩略图类,支持自定义高和宽。还支持按高和宽截图
 代码如下 复制代码

class resizeimage 

    //图片类型 
    var $type; 
    //实际宽度 
    var $width; 
    //实际高度 
    var $height; 
    //改变后的宽度 
    var $resize_width; 
    //改变后的高度 
    var $resize_height; 
    //是否裁图 
    var $cut; 
    //源图象 
    var $srcimg; 
    //目标图象地址 
    var $dstimg; 
    //临时创建的图象 
    var $im; 
    function resizeimage($img, $wid, $hei,$c,$dstpath) 
    { 
        $this->srcimg = $img; 
        $this->resize_width = $wid; 
        $this->resize_height = $hei; 
        $this->cut = $c; 
        //图片的类型 

$this->type = strtolower(substr(strrchr($this->srcimg,"."),1)); 
        //初始化图象 
        $this->initi_img(); 
        //目标图象地址 
        $this -> dst_img($dstpath); 
        //-- 
        $this->width = imagesx($this->im); 
        $this->height = imagesy($this->im); 
        //生成图象 
        $this->newimg(); 
        ImageDestroy ($this->im); 
    } 
    function newimg() 
    { 
        //改变后的图象的比例 
        $resize_ratio = ($this->resize_width)/($this->resize_height); 
        //实际图象的比例 
        $ratio = ($this->width)/($this->height); 
        if(($this->cut)=="1") 
        //裁图 
        { 
            if($ratio>=$resize_ratio) 
            //高度优先 
            { 
                $newimg = imagecreatetruecolor($this->resize_width,$this->resize_height); 
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width,$this->resize_height, (($this->height)*$resize_ratio), $this->height); 
                ImageJpeg ($newimg,$this->dstimg); 
            } 
            if($ratio<$resize_ratio) 
            //宽度优先 
            { 
                $newimg = imagecreatetruecolor($this->resize_width,$this->resize_height); 
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width, $this->resize_height, $this->width, (($this->width)/$resize_ratio)); 
                ImageJpeg ($newimg,$this->dstimg); 
            } 
        } 
        else
        //不裁图 
        { 
            if($ratio>=$resize_ratio) 
            { 
                $newimg = imagecreatetruecolor($this->resize_width,($this->resize_width)/$ratio); 
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width, ($this->resize_width)/$ratio, $this->width, $this->height); 
                ImageJpeg ($newimg,$this->dstimg); 
            } 
            if($ratio<$resize_ratio) 
            { 
                $newimg = imagecreatetruecolor(($this->resize_height)*$ratio,$this->resize_height); 
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, ($this->resize_height)*$ratio, $this->resize_height, $this->width, $this->height); 
                ImageJpeg ($newimg,$this->dstimg); 
            } 
        } 
    } 
    //初始化图象 
    function initi_img() 
    { 
        if($this->type=="jpg") 
        { 
            $this->im = imagecreatefromjpeg($this->srcimg); 
        } 
        if($this->type=="gif") 
        { 
            $this->im = imagecreatefromgif($this->srcimg); 
        } 
        if($this->type=="png") 
        { 
            $this->im = imagecreatefrompng($this->srcimg); 
        } 
    } 
    //图象目标地址 
    function dst_img($dstpath) 
    { 
        $full_length  = strlen($this->srcimg); 
        $type_length  = strlen($this->type); 
        $name_length  = $full_length-$type_length; 

        $name         = substr($this->srcimg,0,$name_length-1); 
        $this->dstimg = $dstpath; 

//echo $this->dstimg; 
    } 

$resizeimage = new resizeimage("11.jpg", "200", "150", "1","17.jpg"); 
?>

实例二

 代码如下 复制代码

<?php

/**
 * 生成缩略图
 * @author yangzhiguo0903@163.com
 * @param string     源图绝对完整地址{带文件名及后缀名}
 * @param string     目标图绝对完整地址{带文件名及后缀名}
 * @param int        缩略图宽{0:此时目标高度不能为0,目标宽度为源图宽*(目标高度/源图高)}
 * @param int        缩略图高{0:此时目标宽度不能为0,目标高度为源图高*(目标宽度/源图宽)}
 * @param int        是否裁切{宽,高必须非0}
 * @param int/float  缩放{0:不缩放, 0<this<1:缩放到相应比例(此时宽高限制和裁切均失效)}
 * @return boolean
 */
function img2thumb($src_img, $dst_img, $width = 75, $height = 75, $cut = 0, $proportion = 0)
{
    if(!is_file($src_img))
    {
        return false;
    }
    $ot = fileext($dst_img);
    $otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
    $srcinfo = getimagesize($src_img);
    $src_w = $srcinfo[0];
    $src_h = $srcinfo[1];
    $type  = strtolower(substr(image_type_to_extension($srcinfo[2]), 1));
    $createfun = 'imagecreatefrom' . ($type == 'jpg' ? 'jpeg' : $type);

    $dst_h = $height;
    $dst_w = $width;
    $x = $y = 0;

    /**
     * 缩略图不超过源图尺寸(前提是宽或高只有一个)
     */
    if(($width> $src_w && $height> $src_h) || ($height> $src_h && $width == 0) || ($width> $src_w && $height == 0))
    {
        $proportion = 1;
    }
    if($width> $src_w)
    {
        $dst_w = $width = $src_w;
    }
    if($height> $src_h)
    {
        $dst_h = $height = $src_h;
    }

    if(!$width && !$height && !$proportion)
    {
        return false;
    }
    if(!$proportion)
    {
        if($cut == 0)
        {
            if($dst_w && $dst_h)
            {
                if($dst_w/$src_w> $dst_h/$src_h)
                {
                    $dst_w = $src_w * ($dst_h / $src_h);
                    $x = 0 - ($dst_w - $width) / 2;
                }
                else
                {
                    $dst_h = $src_h * ($dst_w / $src_w);
                    $y = 0 - ($dst_h - $height) / 2;
                }
            }
            else if($dst_w xor $dst_h)
            {
                if($dst_w && !$dst_h)  //有宽无高
                {
                    $propor = $dst_w / $src_w;
                    $height = $dst_h  = $src_h * $propor;
                }
                else if(!$dst_w && $dst_h)  //有高无宽
                {
                    $propor = $dst_h / $src_h;
                    $width  = $dst_w = $src_w * $propor;
                }
            }
        }
        else
        {
            if(!$dst_h)  //裁剪时无高
            {
                $height = $dst_h = $dst_w;
            }
            if(!$dst_w)  //裁剪时无宽
            {
                $width = $dst_w = $dst_h;
            }
            $propor = min(max($dst_w / $src_w, $dst_h / $src_h), 1);
            $dst_w = (int)round($src_w * $propor);
            $dst_h = (int)round($src_h * $propor);
            $x = ($width - $dst_w) / 2;
            $y = ($height - $dst_h) / 2;
        }
    }
    else
    {
        $proportion = min($proportion, 1);
        $height = $dst_h = $src_h * $proportion;
        $width  = $dst_w = $src_w * $proportion;
    }

    $src = $createfun($src_img);
    $dst = imagecreatetruecolor($width ? $width : $dst_w, $height ? $height : $dst_h);
    $white = imagecolorallocate($dst, 255, 255, 255);
    imagefill($dst, 0, 0, $white);

    if(function_exists('imagecopyresampled'))
    {
        imagecopyresampled($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
    }
    else
    {
        imagecopyresized($dst, $src, $x, $y, 0, 0, $dst_w, $dst_h, $src_w, $src_h);
    }
    $otfunc($dst, $dst_img);
    imagedestroy($dst);
    imagedestroy($src);
    return true;
}

使用方法

 代码如下 复制代码

$src_img = "./ROSI_050_002.JPG";
$dst_img = "./ROSI_050_002_thumb.jpg";
$stat = img2thumb($src_img, $dst_img, $width = 200, $height = 300, $cut = 0, $proportion = 0);
if($stat){
 echo 'Resize Image Success!<br />';
 echo '<img src="'.$dst_img.'" />'; 
}else{
 echo 'Resize Image Fail!'; 
}

php中要给中文加水印需要作一些简单的处理,一就是要把字符转换成gbk,还有就是要加载中文字体哦,有了这两个条件在图片加中文水印就简单了。

例1

 代码如下 复制代码

<?php
Header("Content-type: image/png");      /*通知浏览器,要输出图像*/
$im       = imagecreate(400 , 300);        /*定义图像的大小*/
$gray     = ImageColorAllocate($im , 235 , 235 , 235);
$pink     = ImageColorAllocate($im, 255 , 128 , 255);

$fontfile = "simkai.ttf";

/* $fontfile 字体的路径,视操作系统而定,可以是 simhei.ttf(黑体) , SIMKAI.TTF(楷体) , SIMFANG.TTF(仿宋) ,SIMSUN.TTC(宋体&新宋体) 等 GD 支持的中文字体*/
$str   = iconv('GB2312','UTF-8','中文水印');     /*将 gb2312 的字符集转换成 UTF-8 的字符*/
ImageTTFText($im, 30, 0, 100, 200, $pink , $fontfile , $str);
/* 加入中文水印 */
Imagepng($im);
ImageDestroy($im);
?>

例2

 代码如下 复制代码

<?php
// **************************************** //
// 功能:给图片添加文字
// 参数: $img 图片文件名
// $new_img 另存图片文件名,如果为空表示不另存图片
// $text 字符串内容
// text_size 字符串大小
// text_angle 字型串输出角度
// text_x 字符串输出 x 坐标
// text_y 字符串输出 y 坐标
// $text_font 字型文件名
// $r,$g,$b 字符串颜色RGB值
// **************************************** //
function img_text($img, $new_img, $text, $text_size, $text_angle, $text_x, $text_y, $text_font, $r, $g, $b){

$text=iconv("gb2312","UTF-8",$text);
Header("Content-type: image/gif");
$im = @imagecreatefromstring(file_get_contents($img)) or die ("打开图片失败!");
$color = ImageColorAllocate($im, $r,$g,$b);

//ImageTTFText(int im, int size, int angle, int x, int y, int col, string fontfile, string text):
//本函数将 TTF (TrueType Fonts) 字型文字写入图片。
//参数: size 为字形的尺寸;
// angle 为字型的角度,顺时针计算,0 度为水平(由左到右),90 度则为由下到上的文字;
// x,y 二参数为文字的坐标值 (原点为左上角);
// col 为字的颜色;
// fontfile 为字型文件名称;
// text 是字符串内容。
ImageTTFText($im, $text_size, $text_angle, $text_x, $text_y, $color, $text_font, $text);

if ($new_img==""):
ImageGif($im); // 不保存图片,只显示
else:
ImageGif($im,$new_img); // 保存图片,但不显示
endif;

ImageDestroy($im); //结束图形,释放内存空间
}  
?>

例3

 

 代码如下 复制代码

<?php
/*
* 功能: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 一样。
* 作者:longware @ 2004-11-3 14:15:13
*/
function imageWaterMark($groundImage,$waterPos=0,$waterImage=”",$waterText=”",$textFont=5,$textColor=”#FF0000″)
{
$isWaterImage = FALSE;
$formatMsg = “暂不支持该文件格式,请用图片处理软件将图片转换为GIF、JPG、PNG格式。”;

//读取水印文件
if(!emptyempty($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:die($formatMsg);
}
}

//读取背景图片
if(!emptyempty($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:die($formatMsg);
}
}
else
{
die(”需要加水印的图片不存在!”);
}

//水印位置
if($isWaterImage)//图片水印
{
$w = $water_w;
$h = $water_h;
$label = “图片的”;
}
else//文字水印
{
$temp = imagettfbbox(ceil($textFont*5),0,”./cour.ttf”,$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));
break;
}

//设定图像的混色模式
imagealphablending($ground_im, true);

if($isWaterImage)//图片水印
{
imagecopy($ground_im, $water_im, $posX, $posY, 0, 0, $water_w,$water_h);//拷贝水印到目标文件
}
else//文字水印
{
if( !emptyempty($textColor) && (strlen($textColor)==7) )
{
$R = hexdec(substr($textColor,1,2));
$G = hexdec(substr($textColor,3,2));
$B = hexdec(substr($textColor,5));
}
else
{
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:die($errorMsg);
}

//释放内存
if(isset($water_info)) unset($water_info);
if(isset($water_im)) imagedestroy($water_im);
unset($ground_info);
imagedestroy($ground_im);
}
//—————————————————————————————
$id=$_REQUEST['id'];
$num = count($_FILES['userfile']['name']);
print_r($_FILES['userfile']);
print_r($_FILES['userfile']['name']);

echo $num;
echo “<bR>”;
if(isset($id)){
for($i=0;$i<$id;$i++){

if(isset($_FILES) && !emptyempty($_FILES['userfile']) && $_FILES['userfile']['size']>0)
{
$uploadfile = “./”.time().”_”.$_FILES['userfile'][name][$i];
echo “<br>”;
echo $uploadfile;
if (copy($_FILES['userfile']['tmp_name'][$i], $uploadfile))
{
echo “OK<br>”;

//文字水印
//imageWaterMark($uploadfile,5,”",”HTTP://www.lvye.info”,5,”#cccccc“);

//图片水印
$waterImage=”logo_ok1.gif”;//水印图片路径
imageWaterMark($uploadfile,9,$waterImage);

echo “<img src=”".$uploadfile.”” border=”0”>”;
}
else
{
echo “Fail<br>”;
}
}
}
}

?>
<form enctype=”multipart/form-data” method=”POST”>
<?php
for($a=0;$a<$id;$a++){
echo “文件: <input name=”userfile[]” type=”file”><br>”;

}
?>
<input type=”submit” value=”上传”>
</form>

[!--infotagslink--]

相关文章

  • c#生成高清缩略图的二个示例分享

    这篇文章主要介绍了c#生成高清缩略图的二个示例,需要的朋友可以参考下...2020-06-25
  • PHP批量生成图片缩略图(1/5)

    这款批量生成缩略图代码可以生成指定大小的小图哦,并且支持文件批量上传。 这款教程会用到php文件 view.php config.php funs.php index.php 功能: -------...2016-11-25
  • C#实现为一张大尺寸图片创建缩略图的方法

    这篇文章主要介绍了C#实现为一张大尺寸图片创建缩略图的方法,涉及C#创建缩略图的相关图片操作技巧,需要的朋友可以参考下...2020-06-25
  • php 上传文件并生成缩略图代码

    if( isset($_FILES['upImg']) ) { if( $userGroup[$loginArr['group']]['upload'] == 0 ) { echo '{"error":"您所在的用户组无权上传图片!"}'; } else...2016-11-25
  • CentOS下编译安装nginx及配置缩略图插件的方法教程

    这篇文章主要给大家介绍了在CentOS系统下编译安装nginx及配置缩略图插件的方法教程,文中给出了详细的安装步骤,对大家具有一定的参考价值,有需要的朋友们下面来一起看看吧。...2017-07-06
  • c#多图片上传并生成缩略图的实例代码

    今天写了一个上传多张图片并生成缩略图的小程序。当然因为是菜鸟,所以写的一般。但还是学到了不少东西。现在上代码。...2021-09-22
  • OPPO R9s陌生号码智能识别教程 OPPO R9s如何智能识别陌生号码

    本文介绍了OPPO R9s如何识别陌生号码的方法。这样大家在接电话钱就知道打来的号码他是属于诈骗还是什么性质的号码,因为被别人标记过。那么快跟小编一起来看看吧。...2016-12-31
  • Nginx配合php实现生成实时缩略图功能

    这篇文章主要介绍了Nginx配合php实现生成实时缩略图功能,这在一些特殊场合可能会要用到,需要的朋友可以参考下...2016-01-27
  • C++基于人工智能搜索策略解决农夫过河问题示例

    这篇文章主要介绍了C++基于人工智能搜索策略解决农夫过河问题,简单描述了农夫过河问题的概念、实现原理并结合具体实例形式给出了C++使用人工智能搜索策略解决农夫过河问题的相关操作技巧,需要的朋友可以参考下...2020-04-25
  • js通过canvas生成图片缩略图

    对于生成缩略图一般做法是通过后端语言php等来生成,但是为了给服务器减压,我们或许可以从前端来着手,先生成好不同尺寸的缩略图,传给后端,而后端只需要将前端传过来的图片进行存储就好了...2020-10-03
  • php 图片上传代码(具有生成缩略图与增加水印功能)

    这款图片上传源代码是一款可以上传图片并且还具有给上传的图片生成缩略图与增加水印功能哦,可以说是一款完美的图片上传类哦。 代码如下 复制代码 ...2016-11-25
  • 丁道师:百度押宝人工智能 或可再造一个新百度

    不久前,百度举行了一年一次的百度世界大会,百度董事长兼首席执行官李彦宏表示,互联网正在进入人工智能时代,人工智能将使全社会迎来变革性的发展,百度大脑通过对十多年来的搜索数据、网页数据的‘学习’,在语音、图像、自然语言处理和用户画像上取得了显著成绩。...2016-09-12
  • C# jpg缩略图函数代码

    生成jpg缩略图字节,本人的小软件中需要用到的功能,所以自己做了一个函数,和大家分享 为什么要生成字节而不是文件,这是为了方便后续处理啦^_^...2020-06-25
  • php支持生成缩略图文件上传代码

    <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1...2016-11-25
  • C#获取视频某一帧的缩略图的方法

    这篇文章主要介绍了C#获取视频某一帧的缩略图的方法,涉及执行CMD命令及针对视频文件操作的技巧,具有一定的实用价值,需要的朋友可以参考下...2020-06-25
  • photoshop利用智能对象制作LOGO展示模板分享

    今天小编在这里就来给各位photoshop的这一款软件的使用者们来说下利用智能对象制作LOGO展示模板,各位想知道具体制作方法的软件使用们,那么大家就来跟着小编看一看吧。...2016-11-22
  • php利用Imagick把pdf生成png缩略图

    缩略图如果是图片我们直接使用php gD库就可实现了,本文章要介绍的是Imagick把pdf生成png缩略图方法,这里我们要利用一个插件了,下面我来给大家演示一个实例。 php_im...2016-11-25
  • php图片上传类同时可生成缩略图与加水印

    这款图片上传代码可以把上传的图片增加水印,生成小图片,同时还可以生成文字水印。 代码如下 复制代码 class upimages { var $annexf...2016-11-25
  • ASP.NET创建动态缩略图的方法

    这篇文章主要介绍了ASP.NET创建动态缩略图的方法,实例分析了asp.net动态操作图片的相关技巧,需要的朋友可以参考下...2021-09-22
  • php文件上传程序(支持缩略图)(1/2)

    代码如下 复制代码 <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional....2016-11-25