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

3
我有以下代码用于从用户上传生成缩略图。 它可以生成缩略图,保持纵横比并添加白色背景。 但它将其对齐到左上角。 我需要将其水平和垂直居中。
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个回答

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

这似乎不起作用。请注意,我创建了两个缩略图,一个是180x60,另一个是50x50。上面代码的结果产生了以下内容: 原始图像:(http://malldeals.com/admin/images/logos/1321988719ymca-ywca.jpg) 缩略图1:(http://malldeals.com/admin/images/logos/big1321988719ymca-ywca.jpg) 缩略图2:(http://malldeals.com/admin/images/logos/small1321988719ymca-ywca.jpg) - Jean-Pierre Bazinet

1
我为PHP GD图像编辑制作了一个函数。
PHP-GD-Imagestyle
您可以使用自动大小样式创建居中的缩略图。
$thumb = imagestyle($image,'autosize:250 250');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接