Try this code:
// add this method on your controller and then use resize
function resize($imagePath, $destinationWidth, $destinationHeight, $destinationPath)
{
if (file_exists($imagePath)) {
$imageInfo = getimagesize($imagePath);
$sourceWidth = $imageInfo[0];
$sourceHeight = $imageInfo[1];
$source_aspect_ratio = $sourceWidth/$sourceHeight;
$thumbnail_aspect_ratio = $destinationWidth/$destinationHeight;
if ($sourceWidth <= $destinationWidth && $sourceHeight <= $destinationHeight) {
$thumbnail_image_width = $sourceWidth;
$thumbnail_image_height = $sourceHeight;
} elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
$thumbnail_image_width = (int) ($destinationHeight * $source_aspect_ratio);
$thumbnail_image_height = $destinationHeight;
} else {
$thumbnail_image_width = $destinationWidth;
$thumbnail_image_height = (int) ($destinationWidth/$source_aspect_ratio);
}
$destinationWidth = $thumbnail_image_width;
$destinationHeight = $thumbnail_image_height;
$mimeType = $imageInfo['mime'];
$destinationWidth = $thumbnail_image_width;
$destinationHeight = $thumbnail_image_height;
$destination = imagecreatetruecolor($destinationWidth, $destinationHeight);
if ($mimeType == 'image/jpeg' || $mimeType == 'image/pjpeg') {
$source = imagecreatefromjpeg($imagePath);
imagecopyresampled($destination, $source, 0, 0, 0, 0, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
$destinationPath = $destinationPath;
imagejpeg($destination, $destinationPath);
} else if ($mimeType == 'image/gif') {
$source = imagecreatefromgif($imagePath);
imagecopyresampled($destination, $source, 0, 0, 0, 0, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
$destinationPath = $destinationPath;
imagegif($destination, $destinationPath);
} else if ($mimeType == 'image/png' || $mimeType == 'image/x-png') {
$source = imagecreatefrompng($imagePath);
imagecopyresampled($destination, $source, 0, 0, 0, 0, $destinationWidth, $destinationHeight, $sourceWidth, $sourceHeight);
$destinationPath = $destinationPath;
imagepng($destination, $destinationPath);
} else {
echo 'This image type is not supported.';
}
} else {
echo 'The requested file does not exist.';
}
}
// ==========================================================
$destinationPath = Yii::$app->params['uploadPath'] ."resize/". $model->photo;//note: create new directory (resize) in uploads directory
$this->resize($path, $destinationWidth=100, $destinationHeight=100, $destinationPath);
這個調整工作的比例是多少? – Kshitiz 2014-09-19 05:50:45