Need to center a resized thumbnail

十年热恋 提交于 2019-12-23 17:24:48

问题


I have the following code for generating thumbnails from a user upload. It makes the thumbnail, keeps aspect ratio and adds a white background. But it aligns it to the top left. I need to center it, both horizontally and vertically.

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

回答1:


Something like this might work to replace the last line of code above

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



回答2:


I made a function for PHP GD image editing
PHP-GD-Imagestyle
You can create centered thumbnails by using the autosize style.

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


来源:https://stackoverflow.com/questions/8220840/need-to-center-a-resized-thumbnail

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!