[php] 裁切圖片並縮小至指定大小

/*
 功能:裁切圖片並縮小至指定大小

 參數:
 $_GET['f'] 圖檔名稱:0001.jpg

 $_GET['x'] 圖片裁切水平方向的起始位址(px):10
 $_GET['y'] 圖片裁切垂直方向的起始位址(px):20

 $_GET['w'] 圖片裁切選取的寬度(px):300
 $_GET['h'] 圖片裁切選取的高度(px):200
*/

// 縮小圖片的指定大小(px)
$decreaseSize=160;
     

// 設定 header 中的圖片類型
header("Content-type:image/jpg");

// 檢查是否有給予圖片名稱,否則結束裁切
if (!isset($_GET['f']) || $_GET['f']==''){ exit; }

// 設定 header 中的圖片名稱
header("Content-Disposition:filename=".$_GET['f']);

// 開啟暫存目錄中的圖片
$source = @imageCreateFromJpeg("/tmp/".$_GET['f']);

if (!$source){
    // 圖片開啟錯誤...
    exit;
}




// 取得圖片原始寬度與高度
$sourceWidth  = imagesX($source);
$sourceHeight = imagesY($source);


/* 裁切圖片 */
// 圖片選取的寬度與高度
$cropWidth = intval($_GET['w']);
$cropHeight = intval($_GET['h']);

// 檢查裁切寬度是否在範圍裡
if (!$cropWidth || $cropWidth > $sourceWidth){ // 寬度為零或超過最大寬度
    $cropWidth = $sourceWidth;
}elseif ($cropWidth < $decreaseSize){ // 低於最小寬度
    $cropWidth=$decreaseSize;
}

// 檢查裁切高度是否在範圍裡
if (!$cropHeight || $cropHeight > $sourceHeight){ // 高度為零或超過最大高度
    $cropHeight = $sourceHeight;
}elseif ($cropHeight < $decreaseSize){ // 低於最小高度
    $cropHeight = $decreaseSize;
}


// 圖片選取的起始位址
$cropX = intval($_GET['x']);
$cropY = intval($_GET['y']);

// 檢查起始位址
if ($cropX > ($sourceWidth-$cropWidth)){
    $cropX = $sourceWidth-$cropWidth;
}
if ($cropY > ($sourceHeight-$cropHeight)){
    $cropY = $sourceHeight-$cropHeight;
}


// 建立裁切所需要的圖片空間
$crop = imageCreateTrueColor($cropWidth, $cropHeight);

// 複製選定的圖片範圍(剪裁圖片)
imageCopy(
    $crop,
    $source,
    0,
    0,
    $cropX,
    $cropY,
    $cropWidth,
    $cropHeight
);


/*縮小圖片 */
// 計算縮圖尺寸
if ($cropWidth<$cropHeight) {
    $decreaseWidth = $decreaseSize;
    $decreaseHeight = intval($cropHeight*$decreaseSize/$cropWidth);
} else {
    $decreaseHeight=$decreaseSize;
    $decreaseWidth = intval($cropWidth*$decreaseSize/$cropHeight);
}

// 建立縮圖所需要的圖片空間
$decrease = imageCreateTrueColor($decreaseWidth, $decreaseHeight);

// 複製並縮小圖片
imageCopyResampled(
    $decrease,
    $crop,
    0,
    0,
    0,
    0,
    $decreaseWidth,
    $decreaseHeight,
    $cropWidth,
    $cropHeight
);


// 顯示圖片
imageJpeg($decrease);


// 關閉圖片
imageDestroy($source);
imageDestroy($crop);
imageDestroy($decrease);

留言

這個網誌中的熱門文章

名言-神劍闖江湖

[VPN] windows 7上用bat 自動連接PPTP VPN 並設定ROUTE