php 封裝gd 庫
使用sae 版 thinkphp 在本地和sae 上無法實現縮圖,縮圖主要使用在瀑布流上面,不然一張圖片2 3 M,速度太慢,就自己封裝了一個,見笑!
class Thumb{ // 設定最大寬度,用來在編輯器中使用和顯示 private $max_width = null; private $file_name = null; private $water_name = null; //獲得檔案名稱和圖片寬度 public function __construct($max_widht,$file_name,$water_name) { $this->max_width = $max_widht; $this->file_name = $file_name; $this->water_name = $water_name; } public function create_image(){ // 獲得ori圖片資訊 list($width,$height,$type) = getimagesize($this->file_name); // 當原有圖片大於 要求的最大寬度時,才需要進行壓縮 if($width > $this->max_width){ // 獲得圖片壓縮百分比 $per = $this->max_width / $width; $new_width = $width * $per; $new_height = $height * $per; }else{ $new_height = $height; $new_width = $width; } //建立一個真彩色映像 $image_p = imagecreatetruecolor($new_width, $new_height -10); $image = $this->image_obj($type, $this->file_name); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); $this->image_dump($type, $image_p, $this->file_name); $this->water(); } /* * 產生為圖片添加浮水印 */ private function water(){ $water_name = $this->water_name; $dist_name = $this->file_name; list($dist_width,$dist_height,$type) = getimagesize($dist_name); $dist_im = $this->image_obj($type, $this->file_name); $water_name = "D:/xampps/htdocs/buyingfeiblog/1/App/Modules/Admin/Tpl/Public/Images/water.png"; list($w_width,$w_height) = getimagesize($water_name); // 獲得圖片浮水印資訊 $water_src = imagecreatefrompng($water_name); // 設定圖片浮水印位置 在右下角 $x = ($dist_width - $w_width) / 4 * 3 ; $y =($dist_height - $w_height) /4 * 3 ; if(imagecopy($dist_im, $water_src, $x, $y, 0, 0, $w_width, $w_height)){ imagepng($dist_im,$dist_name); echo "success"; }else{ echo "error"; } } // 產生圖片類型,產生不同圖片 保持圖片原本類型不發生變化 private function image_dump($type,$image_p,$filename){ switch ($type){ case 1: imagegif($image_p, $filename); $dis_im = imagecreatefromgif(file_name); break; case 2: imagejpeg($image_p, $this->file_name); $dis_im = imagecreatefromjpeg(file_name); break; case 3: imagepng($image_p,file_name); $dis_im = imagecreatefrompng(file_name); break; default : } } // 根據圖片不同,產生不同資來源物件 private function image_obj($type,$filename){ switch ($type){// 1 = GIF,2 = JPG,3 = PNG, case 1: $image = imagecreatefromgif($filename); break; case 2: $image = imagecreatefromjpeg($filename); break; case 3: $image = imagecreatefrompng($filename); break; default : } return $image; }} $thumb = new Thumb(725,"D:/xampps/htdocs/test/test.jpg"); $thumb->create_image();//create_image?>
就是這麼簡單,
主要包括產生真彩圖,
建立繪圖物件資源
圖片進行合并,ok!