/usr/bin/convert $sourceFilePath -resize $size -background white -gravity center -extent $size $newFilePathphp
/usr/bin/convert /tmp/test.jpg -resize 500x500 -background white -gravity center -extent 500x500 /tmp/test_500x500.png
意爲將test.jpg縮放(縮小或補充)爲500x500px 圖片居中,背景白色shell
這樣圖片出來後必定是500x500的圖片,放在500x500的div裏面就正好合適且居中code
若不加 -extent 500x500 則圖片就等比縮放,圖片最後尺寸可能不會是500x500,放在500x500的div裏面就會靠左或靠上圖片
===============================get
php計算等比寬高:it
/** 限制圖片寬和高在一個範圍內 文件全路徑,包括文件名,傳入限制的寬 和 高 0爲不限制 返回按等比計算限制以後的寬和高 */ public static function getLimitWH($sourceWidth, $sourceHeight, $maxWidth=0, $maxHeight=0){ //$imgInfo = getimagesize($fileName); $maxWidth = min($sourceWidth, $maxWidth); $maxHeight = min($sourceHeight, $maxHeight); if ($maxWidth && $maxHeight) {//寬高都限制 $tmp_width = intval($sourceWidth*$maxHeight/$sourceHeight);//先按高計算寬 if ($tmp_width > $maxWidth){//若是算出來超出了限制 $maxHeight = intval($sourceHeight*$maxWidth/$sourceWidth);//則按寬計算高 }else{ $maxWidth = $tmp_width; } } elseif ($maxWidth) {//只限制寬 $maxHeight = intval($sourceHeight*$maxWidth/$sourceWidth);//按寬算高 } elseif ($maxHeight) {//只限制高 $maxWidth = intval($sourceWidth*$maxHeight/$sourceHeight);//按高算寬 } return array($maxWidth, $maxHeight); }