這是一款圖象縮略函數,把上傳的新圖片給$srcfile然后進行文件按$thumbwidth 縮小圖寬最大尺寸與$thumbheitht 縮小圖高最大尺寸,生成小圖.
圖象縮略函數,參數說明:
$srcfile 原圖地址; $dir 新圖目錄 $thumbwidth 縮小圖寬最大尺寸 $thumbheitht 縮小圖高最大尺寸 $ratio 默認等比例縮放 為1是縮小到固定尺寸.
php 上傳圖片并按比例生成指定大小圖實例代碼如下:
- function makethumb($srcfile,$dir,$thumbwidth,$thumbheight,$ratio=0)
- {
- //判斷文件是否存在
- if (!file_exists($srcfile))return false;
- //生成新的同名文件,但目錄不同
- $imgname=explode('/',$srcfile);
- $arrcount=count($imgname);
- $dstfile = $dir.$imgname[$arrcount-1];
- //縮略圖大小
- $tow = $thumbwidth;
- $toh = $thumbheight;
- if($tow < 40) $tow = 40;
- if($toh < 45) $toh = 45;
- //獲取圖片信息
- $im ='';
- if($data = getimagesize($srcfile)) {
- if($data[2] == 1) {
- $make_max = 0;//gif不處理
- if(function_exists("imagecreatefromgif")) {
- $im = imagecreatefromgif($srcfile);
- }
- } elseif($data[2] == 2) {
- if(function_exists("imagecreatefromjpeg")) {
- $im = imagecreatefromjpeg($srcfile);
- }
- } elseif($data[2] == 3) {
- if(function_exists("imagecreatefrompng")) {
- $im = imagecreatefrompng($srcfile);
- }
- }
- }
- if(!$im) return '';
- $srcw = imagesx($im);
- $srch = imagesy($im);
- $towh = $tow/$toh;
- $srcwh = $srcw/$srch;
- if($towh <= $srcwh){
- $ftow = $tow;
- $ftoh = $ftow*($srch/$srcw);
- } else {
- $ftoh = $toh;
- $ftow = $ftoh*($srcw/$srch);
- }
- if($ratio){
- $ftow = $tow;
- $ftoh = $toh;
- }
- //縮小圖片
- if($srcw > $tow || $srch > $toh || $ratio) {
- if(function_exists("imagecreatetruecolor") && function_exists("imagecopyresampled") && @$ni = imagecreatetruecolor($ftow, $ftoh)) {
- imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftow, $ftoh, $srcw, $srch);
- } elseif(function_exists("imagecreate") && function_exists("imagecopyresized") && @$ni = imagecreate($ftow, $ftoh)) {
- imagecopyresized($ni, $im, 0, 0, 0, 0, $ftow, $ftoh, $srcw, $srch);
- } else {
- return '';
- }
- if(function_exists('imagejpeg')) {
- imagejpeg($ni, $dstfile);
- } elseif(function_exists('imagepng')) {
- imagepng($ni, $dstfile);
- }
- }else {
- //小于尺寸直接復制
- copy($srcfile,$dstfile);
- }
- imagedestroy($im);
- if(!file_exists($dstfile)) {
- return '';
- } else { //開源代碼Vevb.com
- return $dstfile;
- }
- }
新聞熱點
疑難解答