PHP生成縮略圖(3)--封裝類


前台php代碼

<?php 
require_once 'img_thumb.class.php';
$image = new ImgLib();

//源圖路徑
$src_path='E:/wamp/www/Demo/IMG/01.jpg';
//把新圖片的名稱返回瀏覽器
echo  $image->thumb($src_path,300,300);

 ?>

后台php代碼

 

<?php

class ImgLib{

    private $error;
    public function getError(){

        return $this->error;
    }
/** * * 制作縮略圖 * @param $src_path string 原圖路徑 * @param $max_w int 畫布的寬度 * @param $max_h int 畫布的高度 * @param $flag bool 是否是等比縮略圖 默認為false * @param $prefix string 縮略圖的前綴 默認為'sm_' * */ public function thumb($src_path,$max_w,$max_h,$prefix = 'sm_',$flag = true){ //獲取文件的后綴 $ext= strtolower(strrchr($src_path,'.')); //判斷文件格式 switch($ext){ case '.jpg': $type='jpeg'; break; case '.gif': $type='gif'; break; case '.png': $type='png'; break; default: $this->error='文件格式不正確'; return false; } //拼接打開圖片的函數 $open_fn = 'imagecreatefrom'.$type; //打開源圖 $src = $open_fn($src_path); //創建目標圖 $dst = imagecreatetruecolor($max_w,$max_h); //源圖的寬 $src_w = imagesx($src); //源圖的高 $src_h = imagesy($src); //是否等比縮放 if ($flag) { //等比 //求目標圖片的寬高 if ($max_w/$max_h < $src_w/$src_h) { //橫屏圖片以寬為標准 $dst_w = $max_w; $dst_h = $max_w * $src_h/$src_w; }else{ //豎屏圖片以高為標准 $dst_h = $max_h; $dst_w = $max_h * $src_w/$src_h; } //在目標圖上顯示的位置 $dst_x=(int)(($max_w-$dst_w)/2); $dst_y=(int)(($max_h-$dst_h)/2); }else{ //不等比 $dst_x=0; $dst_y=0; $dst_w=$max_w; $dst_h=$max_h; } //生成縮略圖 imagecopyresampled($dst,$src,$dst_x,$dst_y,0,0,$dst_w,$dst_h,$src_w,$src_h); //文件名 $filename = basename($src_path); //文件夾名 $foldername=substr(dirname($src_path),0); //縮略圖存放路徑 $thumb_path = $foldername.'/'.$prefix.$filename; //把縮略圖上傳到指定的文件夾 imagepng($dst,$thumb_path); //銷毀圖片資源 imagedestroy($dst); imagedestroy($src); //返回新的縮略圖的文件名 return $prefix.$filename; } } ?>

 

結果:

瀏覽器:

文件夾:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM