2011-05-02 23 views
1

我dispaly圖像中的圖像標籤強制上傳的圖片,以保持其比例

<img src="image.jpg" width="100" height="50" /> 

我用戶上傳的圖像大小100×100,我希望它會顯示類似上面的標籤是

<img src="image.jpg" width="50" height="50" /> 

如何實現那個?

ps

我正在使用php,如果它是服務器端問題。

+0

所以你想保持圖像的比例,並設置寬度或高度? – Ben 2011-05-02 21:57:18

+0

不設置,只是爲了保持寬度或高度的限制。如果原始圖片是100x10,標籤是我需要使用整個50像素的寬度,並且只有70像素的高度可用。這將是很多空的空間,但圖像會保持它的形狀。我希望我明白這一點。謝謝。 – eomeroff 2011-05-02 22:12:34

回答

2

使用getimagesize()獲取圖像大小。然後這樣做是爲了縮小到合適的,但保持縱橫比:

if ($width > $height) 
{ 
    $ratio = (float)100/$width; 
} 
else 
{ 
    $ratio = (float)100/$height; 
} 

$width = (int)round($width * $ratio); 
$height = (int)round($height * $ratio); 
0

該代碼將適合爲maxWidth X maxHeight框中的任何圖像,保持縱橫比和填充有白色背景。

$img = new Imagick('orig.jpg'); 
$maxWidth = 100; 
$maxHeight = 50; 

$geom = $img->getImageGeometry(); 
$fitWidth = (($maxWidth/$geom['width'])<($maxHeight/$geom['height']))?true:false; 
if($fitWidth){ 
    $img->thumbnailImage($maxWidth,0,false); 
}else{ 
    $img->thumbnailImage(0,$maxHeight,false); 
} 

$canvas = new Imagick(); 
$canvas->newImage($maxWidth,$maxHeight,'white','jpg'); 

$geom = $img->getImageGeometry(); 
$x = ($maxWidth-$geom['width'])/2; 
$y = ($maxHeight-$geom['height'])/2; 
$canvas->compositeImage($img,imagick::COMPOSITE_OVER,$x,$y); 

$canvas->writeImage('thumb.jpg'); 
相關問題