標籤:
<?php
/**
* Created by PhpStorm.
* User: 蘭小宇
* Date: 2016/3/30
* Time: 23:08
*/
//影像處理類
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->getType($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_w = 0;
$cut_h = 0;
//判斷原始映像的寬和高
if ($this->width < $this->height) { //如果原始映像的寬比他的高度小
//讓長度和新高度等比例
$new_width = ($new_height / $this->height) * $this->width; //新的寬度等於新的高度除以原來的高度再乘以原來的寬度
//公式解釋:在等比例的裁剪中,我們首先要找到等比例的因子,就是按照什麼樣的比例來進行縮放的
//如果款比高小,那我們就用新的高度,除以老的高度,得到一個等比例的百分數,然後乘以元來的寬度等於新的寬度
//例如:原來的是500*1000 ,設定的寬和高為150 * 50
//那麼新的寬度等於 (50/1000)*500
}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,0,0,$new_width,$new_height,$this->width,$this->height);
}
//判斷映像類型,然後載入映像資源
private function getType($file,$type){
$img = ‘‘;
switch($type){
case 1:
$img = imagecreatefromgif($file);
break;
case 2:
$img = imagecreatefromjpeg($file);
break;
case 3:
$img = imagecreatefrompng($file);
break;
default:
Tool::alertBack(‘請上傳圖片類型為gif,jpg,png的檔案!‘);
}
return $img;
}
//映像輸出
public function out(){
imagepng($this->new,$this->file);//輸出
imagedestroy($this->img);//銷毀資源
imagedestroy($this->new);//銷毀
}
}
學習筆記-php映像簡單完美剪裁-2016.4.7