使用PHP實現生成固定大小圖片縮圖功能(智慧裁剪,圖片不失真)
阿新 • • 發佈:2019-02-01
<?php //影象處理類 class Image { private $file; //圖片地址 private $width; //圖片長度 private $height; //圖片長度 private $type; //圖片型別 private $img; //原圖的資源控制代碼 private $new; //新圖的資源控制代碼 //構造方法,初始化 public function __construct($_file) { $this->file = $_SERVER["DOCUMENT_ROOT"].$_file; list($this->width, $this->height, $this->type) = getimagesize($this->file); $this->img = $this->getFromImg($this->file, $this->type); } //縮圖(固定長高容器,影象等比例,擴容填充,裁剪)[固定了大小,不失真,不變形] public function thumb($new_width = 0,$new_height = 0) { if (empty($new_width) && empty($new_height)) { $new_width = $this->width; $new_height = $this->height; } if (!is_numeric($new_width) || !is_numeric($new_height)) { $new_width = $this->width; $new_height = $this->height; } //建立一個容器 $_n_w = $new_width; $_n_h = $new_height; //建立裁剪點 $_cut_width = 0; $_cut_height = 0; if ($this->width < $this->height) { $new_width = ($new_height / $this->height) * $this->width; } else { $new_height = ($new_width / $this->width) * $this->height; } if ($new_width < $_n_w) { //如果新高度小於新容器高度 $r = $_n_w / $new_width; //按長度求出等比例因子 $new_width *= $r; //擴充套件填充後的長度 $new_height *= $r; //擴充套件填充後的高度 $_cut_height = ($new_height - $_n_h) / 2; //求出裁剪點的高度 } if ($new_height < $_n_h) { //如果新高度小於容器高度 $r = $_n_h / $new_height; //按高度求出等比例因子 $new_width *= $r; //擴充套件填充後的長度 $new_height *= $r; //擴充套件填充後的高度 $_cut_width = ($new_width - $_n_w) / 2; //求出裁剪點的長度 } $this->new = imagecreatetruecolor($_n_w,$_n_h); imagecopyresampled($this->new,$this->img,0,0,$_cut_width,$_cut_height,$new_width,$new_height,$this->width,$this->height); } //載入圖片,各種型別,返回圖片的資源控制代碼 private function getFromImg($_file, $_type) { switch ($_type) { case 1 : $img = imagecreatefromgif($_file); break; case 2 : $img = imagecreatefromjpeg($_file); break; case 3 : $img = imagecreatefrompng($_file); break; default: Tool::alertBack('警告:此圖片型別本系統不支援!'); } return $img; } //影象輸出 public function out() { imagepng($this->new,$this->file); imagedestroy($this->img); imagedestroy($this->new); } } ?> //使用方法: $_path = 'd:/1.jpg'; $_img = new Image($_path);//$_path為圖片檔案的路徑 $_img->thumb(150, 100); $_img->out();