2014-03-13 142 views
0

我使用下面的代碼在PHP中生成圖像縮略圖。它會生成與圖像高度和寬度尺寸成比例的縮略圖。如何在300X200尺寸的PHP中生成圖像縮略圖?

make_thumb('images/image.jpg', 'images-generated-thumbs/7.jpg', 300, 200); 

function make_thumb($src, $dest, $desired_width, $desired_height) { 

    /* read the source image */ 
    $source_image = imagecreatefromjpeg($src); 
    $width = imagesx($source_image); 
    $height = imagesy($source_image); 

    /* find the "desired height" of this thumbnail, relative to the desired width */ 
    $desired_height = floor($height*($desired_width/$width)); 
    $desired_width = floor($width*($desired_height/$height)); 

    /* create a new, "virtual" image */ 
    $virtual_image = imagecreatetruecolor($desired_width, $desired_height); 

    /* copy source image at a resized size */ 
    imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height); 

    /* create the physical thumbnail image to its destination */ 
    imagejpeg($virtual_image, $dest); 
} 

對於上面的例子,它生成的縮略圖7.jpg與大小299x187。所以,我的問題是如何填充白色的其餘像素((300-299)×(300-187))。 如果我們刪除上面的代碼中的$desired_height變量,它會生成寬度爲300的縮略圖,因此只需要用白色填充其餘高度。

+0

爲什麼你需要有這些縮略圖嚴格尺寸300 * 200? –

回答

2

在修改寬度/高度,它們存儲:

$actual_width = $desired_width; 
$actual_height = $desired_height; 
$desired_height = floor($height*($desired_width/$width)); 
$desired_width = floor($width*($desired_height/$height)); 

當你正在做的帆布:

/* create a new, "virtual" image */ 
$virtual_image = imagecreatetruecolor($actual_width, $actual_height); 

在這一點上的虛擬形象是黑色,用白色填充它:

$white = imagecolorallocate($virtual_image, 255, 255, 255); 
imagefill($virtual_image, 0, 0, $white); 
+0

太好了,謝謝你的回覆。 – Sami