廣告招牌設計巧思運用,靈活搭配字型
燈光、安裝位置,幫您高調搶商機
油漆工程居住高品質的隔音門,無聲靜悄悄
引領業界,專營各式門窗,提供免費到府丈量

首頁  •  j2h 論壇 • 程式設計討論     • 

[php] Resize Image

房東:王小姐
發表時間:2017-11-17
[檢舉]



在開發網頁中,圖片放大縮小或更改高度、寬度是常有的問題

除了用一些軟體可以處理之外,PHP原生的函式中對於這部份也可以處理


class ResizeImage {
var $image;
var $image_type_id;
function load($filename) {
//取得圖片資訊
$image_info = getimagesize($filename);
//取得圖片類型
$this -> image_type_id = $image_info[2];
//判斷圖片類型,並建立圖片物件
if( $this -> image_type_id == IMAGETYPE_JPEG ) {
$this -> image = imagecreatefromjpeg($filename);
}
elseif( $this -> image_type_id == IMAGETYPE_GIF ) {
$this -> image = imagecreatefromgif($filename);
}
elseif( $this -> image_type_id == IMAGETYPE_PNG )
{
$this -> image = imagecreatefrompng($filename);
}
}

function save($filename, $image_type_id = IMAGETYPE_JPEG) {
if( $image_type_id == IMAGETYPE_JPEG ) {
imagejpeg($this -> image,$filename,75);
}
elseif( $image_type_id == IMAGETYPE_GIF ) {
imagegif($this -> image,$filename);
}
elseif( $image_type_id == IMAGETYPE_PNG ) {
imagepng($this -> image,$filename);
}
//修改權限
chmod($filename,0755);
}

function getWidth() {
//取得寬度
return imagesx($this -> image);
}
function getHeight() {
//取得高度
return imagesy($this -> image);
}
function resizeToHeight($height) {
//高度縮放(寬度等比縮放)
$ratio = $height / $this -> getHeight();
$width = $this -> getWidth() * $ratio;
$this->resize($width,$height);
}

function resizeToWidth($width) {
//寬度縮放(高度等比縮放)
$ratio = $width / $this -> getWidth();
$height = $this -> getheight() * $ratio;
$this->resize($width,$height);
}

function scale($scale) {
//百分比縮放
$width = $this -> getWidth() * $scale/100;
$height = $this -> getheight() * $scale/100;
$this->resize($width,$height);
}

function resize($width,$height) {
//imagecreatetruecolor會產生特定長寬的黑色圖形,並建立圖片物件
$new_image = imagecreatetruecolor($width, $height);
//利用imagecopyresampled resize圖片
//imagecopyresampled(目地圖片,來源圖片,目地x座標,目地y座標,來源x座標,來源y座標,目地寬度,目地高度,來源寬度,來源高度)
imagecopyresampled($new_image, $this -> image, 0, 0, 0, 0, $width, $height, $this -> getWidth(), $this -> getHeight());
//將image變數指向新的圖片
$this -> image = $new_image;
}
}











範例:


$image = new ResizeImage();
$image -> load(\"johnson.jpg\");
//縮放至120%
$image -> scale(120);
$image -> save(\'pic1.jpg\');
//修改高度
$image->resizeToHeight(500);
$image->save(\'pic2.jpg\');



  • 贊助網站       

    廣利不動產-板橋在地生根最實在--新板特區指名度最高、值得您信賴的好房仲
    完整房訊,房屋、店面熱門精選物件,廣利不動產 優質仲介,房屋租賃、買賣資訊透明,交易真安心!
    廣利不動產-新板特區指名度最高、值得您信賴的好房仲
    您的托付,廣利用心為您服務



  •  共 0 人回應

    姓名:
    佈告內容: