php生成图片缩略图类程序

 更新时间:2016年11月25日 16:56  点击:1271
缩略图用得最多的是我们上传图片时生成一张小图,这样就可以很好的解决图片大小或影响网站整体美观的问题了,下面介绍的生成图片缩略图类都不支持图片上传,我们要先上传再调用此类来操作。

//使用如下类就可以生成图片缩略图,

 代码如下 复制代码

<?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("图片源文件地址", "200", "100", "0","缩略图地址");

//就只用上面的一句话,就能生成缩略图,其中,源文件和缩略图地址可以相同,200,100分别代表宽和高

实例2

PHP缩略图 等比例无损压缩,可填充空白区域补充色

 代码如下 复制代码

<?php
error_reporting( E_ALL );

// 测试
imagezoom('1.jpg', '2.jpg', 400, 300, '#FFFFFF');

/*
    php缩略图函数:
        等比例无损压缩,可填充补充色 author: 华仔
    主持格式:
        bmp 、jpg 、gif、png
    param:
        @srcimage : 要缩小的图片
        @dstimage : 要保存的图片
        @dst_width: 缩小宽
        @dst_height: 缩小高
        @backgroundcolor: 补充色  如:#FFFFFF  支持 6位  不支持3位
*/
function imagezoom( $srcimage, $dstimage,  $dst_width, $dst_height, $backgroundcolor ) {
       
        // 中文件名乱码
        if ( PHP_OS == 'WINNT' ) {
                $srcimage = iconv('UTF-8', 'GBK', $srcimage);
                $dstimage = iconv('UTF-8', 'GBK', $dstimage);
        }
   
    $dstimg = imagecreatetruecolor( $dst_width, $dst_height );
    $color = imagecolorallocate($dstimg
        , hexdec(substr($backgroundcolor, 1, 2))
        , hexdec(substr($backgroundcolor, 3, 2))
        , hexdec(substr($backgroundcolor, 5, 2))
    );
    imagefill($dstimg, 0, 0, $color);
   
    if ( !$arr=getimagesize($srcimage) ) {
                echo "要生成缩略图的文件不存在";
                exit;
        }
       
    $src_width = $arr[0];
    $src_height = $arr[1];
    $srcimg = null;
    $method = getcreatemethod( $srcimage );
    if ( $method ) {
        eval( '$srcimg = ' . $method . ';' );
    }
   
    $dst_x = 0;
    $dst_y = 0;
    $dst_w = $dst_width;
    $dst_h = $dst_height;
    if ( ($dst_width / $dst_height - $src_width / $src_height) > 0 ) {
        $dst_w = $src_width * ( $dst_height / $src_height );
        $dst_x = ( $dst_width - $dst_w ) / 2;
    } elseif ( ($dst_width / $dst_height - $src_width / $src_height) < 0 ) {
        $dst_h = $src_height * ( $dst_width / $src_width );
        $dst_y = ( $dst_height - $dst_h ) / 2;
    }

    imagecopyresampled($dstimg, $srcimg, $dst_x
        , $dst_y, 0, 0, $dst_w, $dst_h, $src_width, $src_height);
   
    // 保存格式
    $arr = array(
        'jpg' => 'imagejpeg'
        , 'jpeg' => 'imagejpeg'
        , 'png' => 'imagepng'
        , 'gif' => 'imagegif'
        , 'bmp' => 'imagebmp'
    );
    $suffix = strtolower( array_pop(explode('.', $dstimage ) ) );
    if (!in_array($suffix, array_keys($arr)) ) {
        echo "保存的文件名错误";
        exit;
    } else {
        eval( $arr[$suffix] . '($dstimg, "'.$dstimage.'");' );
    }
   
    imagejpeg($dstimg, $dstimage);
   
    imagedestroy($dstimg);
    imagedestroy($srcimg);
   
}


function getcreatemethod( $file ) {
        $arr = array(
                '474946' => "imagecreatefromgif('$file')"
                , 'FFD8FF' => "imagecreatefromjpeg('$file')"
                , '424D' => "imagecreatefrombmp('$file')"
                , '89504E' => "imagecreatefrompng('$file')"
        );
        $fd = fopen( $file, "rb" );
        $data = fread( $fd, 3 );
       
        $data = str2hex( $data );
       
        if ( array_key_exists( $data, $arr ) ) {
                return $arr[$data];
        } elseif ( array_key_exists( substr($data, 0, 4), $arr ) ) {
                return $arr[substr($data, 0, 4)];
        } else {
                return false;
        }
}

function str2hex( $str ) {
        $ret = "";
       
        for( $i = 0; $i < strlen( $str ) ; $i++ ) {
                $ret .= ord($str[$i]) >= 16 ? strval( dechex( ord($str[$i]) ) )
                        : '0'. strval( dechex( ord($str[$i]) ) );
        }
       
        return strtoupper( $ret );
}

// BMP 创建函数  php本身无
function imagecreatefrombmp($filename)
{
   if (! $f1 = fopen($filename,"rb")) return FALSE;

   $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
   if ($FILE['file_type'] != 19778) return FALSE;

   $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
   $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
   if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
   $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
   $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
   $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] = 4-(4*$BMP['decal']);
   if ($BMP['decal'] == 4) $BMP['decal'] = 0;
  
   $PALETTE = array();
   if ($BMP['colors'] < 16777216)
   {
    $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
   }
  
   $IMG = fread($f1,$BMP['size_bitmap']);
   $VIDE = chr(0);

   $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
   $P = 0;
   $Y = $BMP['height']-1;
   while ($Y >= 0)
   {
        $X=0;
        while ($X < $BMP['width'])
        {
         if ($BMP['bits_per_pixel'] == 24)
            $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
         elseif ($BMP['bits_per_pixel'] == 16)
         { 
            $COLOR = unpack("n",substr($IMG,$P,2));
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 8)
         { 
            $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 4)
         {
            $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
            if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 1)
         {
            $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
            if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
            elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
            elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
            elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
            elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
            elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
            elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
            elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         else
            return FALSE;
         imagesetpixel($res,$X,$Y,$COLOR[1]);
         $X++;
         $P += $BMP['bytes_per_pixel'];
        }
        $Y--;
        $P+=$BMP['decal'];
   }
   fclose($f1);

return $res;
}
// BMP 保存函数,php本身无
function imagebmp ($im, $fn = false)
{
    if (!$im) return false;
           
    if ($fn === false) $fn = 'php://output';
    $f = fopen ($fn, "w");
    if (!$f) return false;
           
    $biWidth = imagesx ($im);
    $biHeight = imagesy ($im);
    $biBPLine = $biWidth * 3;
    $biStride = ($biBPLine + 3) & ~3;
    $biSizeImage = $biStride * $biHeight;
    $bfOffBits = 54;
    $bfSize = $bfOffBits + $biSizeImage;
           
    fwrite ($f, 'BM', 2);
    fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));
           
    fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));
           
    $numpad = $biStride - $biBPLine;
    for ($y = $biHeight - 1; $y >= 0; --$y)
    {
        for ($x = 0; $x < $biWidth; ++$x)
        {
            $col = imagecolorat ($im, $x, $y);
            fwrite ($f, pack ('V', $col), 3);
        }
        for ($i = 0; $i < $numpad; ++$i)
            fwrite ($f, pack ('C', 0));
    }
    fclose ($f);
    return true;
}

?>

总结,第一个类文件不如第二个好,因为第一个生成图之后图片会有点变模糊哦,后面这个生成类是高质量的。

一个简单的使用php上传图片文件生然后再生成一张等比例的缩略图效果,有需要学习的朋友可参考参考。
 代码如下 复制代码

 

<?php
function _UPLOADPIC($upfile, $maxsize, $updir, $newname = 'date') {

if ($newname == 'date')

$newname = date ( "Ymdhis" ); //使用日期做文件名 

$name = $upfile ["name"];

$type = $upfile ["type"];

$size = $upfile ["size"];

$tmp_name = $upfile ["tmp_name"];

switch ($type) {

case 'image/pjpeg' :

case 'image/jpeg' :

$extend = ".jpg";

break;

case 'image/gif' :

$extend = ".gif";

break;

case 'image/png' :

$extend = ".png";

break;

}

if (emptyempty ( $extend )) {

echo ( "警告!只能上传图片类型:GIF JPG PNG" );

exit ();

}

if ($size > $maxsize) {

$maxpr = $maxsize / 1000;

echo ( "警告!上传图片大小不能超过" . $maxpr . "K!" );

exit ();

}

if (move_uploaded_file ( $tmp_name, $updir . $newname . $extend )) {

return $updir . $newname . $extend;

}

}

 

function show_pic_scal($width, $height, $picpath) {

$imginfo = GetImageSize ( $picpath );

$imgw = $imginfo [0];

$imgh = $imginfo [1];

 

$ra = number_format ( ($imgw / $imgh), 1 ); //宽高比

$ra2 = number_format ( ($imgh / $imgw), 1 ); //高宽比

 

 

if ($imgw > $width or $imgh > $height) {

if ($imgw > $imgh) {

$newWidth = $width;

$newHeight = round ( $newWidth / $ra );

 

} elseif ($imgw < $imgh) {

$newHeight = $height;

$newWidth = round ( $newHeight / $ra2 );

} else {

$newWidth = $width;

$newHeight = round ( $newWidth / $ra );

}

} else {

$newHeight = $imgh;

$newWidth = $imgw;

}

$newsize [0] = $newWidth;

$newsize [1] = $newHeight;

 

return $newsize;

}

 

 

 

function getImageInfo($src)

{

return getimagesize($src);

}

/**

* 创建图片,返回资源类型

* @param string $src 图片路径

* @return resource $im 返回资源类型 

* **/ 

function create($src)

{

$info=getImageInfo($src);

switch ($info[2])

{

case 1:

$im=imagecreatefromgif($src);

break;

case 2:

$im=imagecreatefromjpeg($src);

break;

case 3:

$im=imagecreatefrompng($src);

break;

}

return $im;

}

/**

* 缩略图主函数

* @param string $src 图片路径

* @param int $w 缩略图宽度

* @param int $h 缩略图高度

* @return mixed 返回缩略图路径

* **/ 

 

function resize($src,$w,$h)

{

$temp=pathinfo($src);

$name=$temp["basename"];//文件名

$dir=$temp["dirname"];//文件所在的文件夹

$extension=$temp["extension"];//文件扩展名

$savepath="{$dir}/{$name}";//缩略图保存路径,新的文件名为*.thumb.jpg

 

//获取图片的基本信息

$info=getImageInfo($src);

$width=$info[0];//获取图片宽度

$height=$info[1];//获取图片高度

$per1=round($width/$height,2);//计算原图长宽比

$per2=round($w/$h,2);//计算缩略图长宽比

 

//计算缩放比例

if($per1>$per2||$per1==$per2)

{

//原图长宽比大于或者等于缩略图长宽比,则按照宽度优先

$per=$w/$width;

}

if($per1<$per2)

{

//原图长宽比小于缩略图长宽比,则按照高度优先

$per=$h/$height;

}

$temp_w=intval($width*$per);//计算原图缩放后的宽度

$temp_h=intval($height*$per);//计算原图缩放后的高度

$temp_img=imagecreatetruecolor($temp_w,$temp_h);//创建画布

$im=create($src);

imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height);

if($per1>$per2)

{

imagejpeg($temp_img,$savepath, 100);

imagedestroy($im);

return addBg($savepath,$w,$h,"w");

//宽度优先,在缩放之后高度不足的情况下补上背景

}

if($per1==$per2)

{

imagejpeg($temp_img,$savepath, 100);

imagedestroy($im);

return $savepath;

//等比缩放

}

if($per1<$per2)

{

imagejpeg($temp_img,$savepath, 100);

imagedestroy($im);

return addBg($savepath,$w,$h,"h");

//高度优先,在缩放之后宽度不足的情况下补上背景

}

}

/**

* 添加背景

* @param string $src 图片路径

* @param int $w 背景图像宽度

* @param int $h 背景图像高度

* @param String $first 决定图像最终位置的,w 宽度优先 h 高度优先 wh:等比

* @return 返回加上背景的图片

* **/ 

function addBg($src,$w,$h,$fisrt="w")

{

$bg=imagecreatetruecolor($w,$h);

$white = imagecolorallocate($bg,255,255,255);

imagefill($bg,0,0,$white);//填充背景

 

//获取目标图片信息

$info=getImageInfo($src);

$width=$info[0];//目标图片宽度

$height=$info[1];//目标图片高度

$img=create($src);

if($fisrt=="wh")

{

//等比缩放

return $src;

}

else 

{

if($fisrt=="w")

{

$x=0;

$y=($h-$height)/2;//垂直居中

}

if($fisrt=="h")

{

$x=($w-$width)/2;//水平居中

$y=0;

}

imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);

imagejpeg($bg,$src,100);

imagedestroy($bg);

imagedestroy($img);

return $src;

}
}
?> 

使用方法: 

$filename=(_UPLOADPIC($_FILES["upload"],$maxsize,$updir,$newname='date'));
$show_pic_scal=show_pic_scal(230, 230, $filename);
resize($filename,$show_pic_scal[0],$show_pic_scal[1]);

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
  
 /***************************************  *作者:落梦天蝎(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;
         }
     }
  
 }
 ?>
在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;
 }
}

[!--infotagslink--]

相关文章

  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • C#使用Process类调用外部exe程序

    本文通过两个示例讲解了一下Process类调用外部应用程序的基本用法,并简单讲解了StartInfo属性,有需要的朋友可以参考一下。...2020-06-25
  • 微信小程序 页面传值详解

    这篇文章主要介绍了微信小程序 页面传值详解的相关资料,需要的朋友可以参考下...2017-03-13
  • 使用GruntJS构建Web程序之构建篇

    大概有如下步骤 新建项目Bejs 新建文件package.json 新建文件Gruntfile.js 命令行执行grunt任务 一、新建项目Bejs源码放在src下,该目录有两个js文件,selector.js和ajax.js。编译后代码放在dest,这个grunt会...2014-06-07
  • uniapp微信小程序:key失效的解决方法

    这篇文章主要介绍了uniapp微信小程序:key失效的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-20
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • 将c#编写的程序打包成应用程序的实现步骤分享(安装,卸载) 图文

    时常会写用c#一些程序,但如何将他们和photoshop一样的大型软件打成一个压缩包,以便于发布....2020-06-25
  • 微信小程序 网络请求(GET请求)详解

    这篇文章主要介绍了微信小程序 网络请求(GET请求)详解的相关资料,需要的朋友可以参考下...2016-11-22
  • 微信小程序二维码生成工具 weapp-qrcode详解

    这篇文章主要介绍了微信小程序 二维码生成工具 weapp-qrcode详解,教大家如何在项目中引入weapp-qrcode.js文件,通过实例代码给大家介绍的非常详细,需要的朋友可以参考下...2021-10-23
  • 微信小程序自定义tabbar组件

    这篇文章主要为大家详细介绍了微信小程序自定义tabbar组件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-03-14
  • 微信小程序如何获取图片宽度与高度

    这篇文章主要给大家介绍了关于微信小程序如何获取图片宽度与高度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
  • Python爬取微信小程序通用方法代码实例详解

    这篇文章主要介绍了Python爬取微信小程序通用方法代码实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-29
  • 手把手教你uniapp和小程序分包(图文)

    本文主要介绍了手把手教你uniapp和小程序分包,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-02
  • 微信小程序(应用号)开发新闻客户端实例

    这篇文章主要介绍了微信小程序(应用号)开发新闻客户端实例的相关资料,需要的朋友可以参考下...2016-10-25
  • 微信小程序 页面跳转传递值几种方法详解

    这篇文章主要介绍了微信小程序 页面跳转传递值几种方法详解的相关资料,需要的朋友可以参考下...2017-01-16
  • 微信小程序手势操作之单触摸点与多触摸点

    这篇文章主要介绍了微信小程序手势操作之单触摸点与多触摸点的相关资料,需要的朋友可以参考下...2017-03-13
  • 微信小程序实现canvas分享朋友圈海报

    这篇文章主要为大家详细介绍了微信小程序实现canvas分享朋友圈海报,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-21
  • 微信小程序实现选择地址省市区三级联动

    这篇文章主要为大家详细介绍了微信小程序实现选择地址省市区三级联动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-21
  • uniapp,微信小程序中使用 MQTT的问题

    这篇文章主要介绍了uniapp,微信小程序中使用 MQTT的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-07-11