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


Need to center a resized thumbnail

我有以下代码从用户上传生成缩略图。它使缩略图,保持长宽比,并添加一个白色的背景。但它会对齐到左上角。我需要在水平方向和垂直方向把它居中

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));

类似这样的代码可以用来替换

上面的最后一行代码
$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));

我编写了一个PHP GD图像编辑函数
PHP-GD-Imagestyle
您可以使用autosize样式创建居中缩略图。

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