本示例將縮小圖像以適合創建不超過指定限制(1200 x 675)的圖像的定義像素完美寬高比(16:9)。
設置你的圖像比和任何上限:
const RATIO_W = 16;
const RATIO_H = 9;
const RATIO_MULIPLIER_UPPER_LIMIT = 75;
通過因子計算新的圖像的寬度和高度
list($imageWidth, $imageHeight) = getimagesize($path_to_image);
if(($imageWidth/$imageHeight) === (self::RATIO_W/self::RATIO_H)){
return;
// Find closest ratio multiple to image size
if($imageWidth > $imageHeight){
// landscape
$ratioMultiple = round($imageHeight/self::RATIO_H, 0, PHP_ROUND_HALF_DOWN);
}else{
// portrait
$ratioMultiple = round($imageWidth/self::RATIO_W, 0, PHP_ROUND_HALF_DOWN);
}
$newWidth = $ratioMultiple * self::RATIO_W;
$newHeight = $ratioMultiple * self::RATIO_H;
if($newWidth > self::RATIO_W * self::RATIO_MULIPLIER_UPPER_LIMIT|| $newHeight > self::RATIO_H * self::RATIO_MULIPLIER_UPPER_LIMIT){
// File is larger than upper limit
$ratioMultiple = self::RATIO_MULIPLIER_UPPER_LIMIT;
}
$this->tweakMultiplier($ratioMultiple, $imageWidth, $imageHeight);
$newWidth = $ratioMultiple * self::RATIO_W;
$newHeight = $ratioMultiple * self::RATIO_H;
調整尺寸圖像
$originalImage = imagecreatefromjpeg($tempImagePath);
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, imagecolorallocate($newImage, 255, 255, 255));
imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $imageWidth, $imageHeight);
imagejpeg($newImage, $tempImagePath, 100);
循環直到兩個尺寸小於原始圖像尺寸
protected function tweakMultiplier(&$ratioMultiple, $fitInsideWidth, $fitInsideHeight){
$newWidth = $ratioMultiple * self::RATIO_W;
$newHeight = $ratioMultiple * self::RATIO_H;
if($newWidth > $fitInsideWidth || $newHeight > $fitInsideHeight){
echo " Tweak ";
$ratioMultiple--;
$this->tweakMultiplier($ratioMultiple, $fitInsideWidth, $fitInsideHeight);
}else{
return;
}
}
的可能重複[圖片縮小問題(PHP/GD)](http://stackoverflow.com/questions/1830829/image-resizing-question-php-gd) – hakre
已經寫了一個擴展類,檢查它:https://github.com/qaribhaider/php-image-resize –