需要居中调整大小的缩略图

时间:2011-11-22 01:21:19

标签: php gd

我有以下代码用于从用户上传生成缩略图。 它使缩略图,保持纵横比并添加白色背景。 但它将它与左上角对齐。 我需要水平和垂直居中。

function makethumbnail($thumbw,$thumbh,$thumbName,$sourceName){

$ext=getExtension($sourceName);
//echo $ext;
$sourcePath = 'images/logos/deals/'; // Path of original image
$sourceUrl = 'http://www.malldeals.com/admin/convert/';
$thumbPath = $sourcePath; // Writeable thumb path
$thumbUrl = $sourceUrl . $thumbPath ;
$thumbHeight=0;
$thumbWidth=0;
// Beyond this point is simply code.
if(!strcmp("png",$ext))
    $sourceImage = imagecreatefrompng("$sourcePath/$sourceName");   
else if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
    $sourceImage = imagecreatefromjpeg("$sourcePath/$sourceName");  
else if(!strcmp("gif",$ext))
    $sourceImage = imagecreatefromgif("$sourcePath/$sourceName");   
            global $sourceWidth, $sourceHeight;
            $sourceWidth = imagesx($sourceImage);
            $sourceHeight = imagesy($sourceImage);

$ratio1=$sourceWidth/$thumbw;
$ratio2=$sourceHeight/$thumbh;
if($ratio1>$ratio2) {
    $thumbWidth=$thumbw;
    $thumbHeight=$sourceHeight/$ratio1;
}
else {
    $thumbHeight=$thumbh;
    $thumbWidth=$sourceWidth/$ratio2;
}


$targetImage = imagecreatetruecolor($thumbw,$thumbh);

    // get the color white
    $color = imagecolorallocate($targetImage, 255, 255, 255);

    // fill entire image
    imagefill($targetImage, 0, 0, $color);
imagecopyresampled($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbHeight,imagesx($sourceImage),imagesy($sourceImage));

2 个答案:

答案 0 :(得分:1)

这样的事情可能会取代上面的最后一行代码

$offsetx = round((imagesx($sourceImage) - $thumbw) / 2);
$offsety = round((imagesy($sourceImage) - $thumbh) / 2);

imagecopyresampled($targetImage,$sourceImage,$offsetx,$offsety,
0,0,$thumbWidth,$thumbHeight,imagesx($sourceImage),imagesy($sourceImage));

答案 1 :(得分:1)

我为PHP GD图像编辑做了一个功能 PHP-GD-Imagestyle
您可以使用自动调整样式创建居中缩略图。

$thumb = imagestyle($image,'autosize:250 250');