2016-02-09 96 views
1

我想将图像大小调整为正方形。假设我想要一个500x500的平方图像,并且我有一个300x600的图像 我想将图像大小调整为200x500,然后为其添加白色背景以使其成为500x500调整图像大小 - 保持比例 - 添加白色背景

我通过这样做了一些很好的工作:

$TargetImage = imagecreatetruecolor(300, 600); 
imagecopyresampled(
    $TargetImage, $SourceImage, 
    0, 0, 
    0, 0, 
    300, 600, 
    500, 500 
); 
$final = imagecreatetruecolor(500, 500); 
$bg_color = imagecolorallocate ($final, 255, 255, 255) 
imagefill($final, 0, 0, $bg_color); 
imagecopyresampled(
    $final, $TargetImage, 
    0, 0, 
    ($x_mid - (500/ 2)), ($y_mid - (500/ 2)), 
    500, 500, 
    500, 500 
); 

它几乎所有事情都做对了。图片集中在一切。除了背景是黑色而不是白色:/

任何人都知道我在做什么错了?

picture

+0

据我所知,这不能用PHP来完成。 –

+0

您可能需要使用像[imagemagick](http://php.net/manual/en/intro.imagick.php)这样的扩展名。特别是如果其他附加图像操作在地平线上。 –

+0

您能提供原始图像宽度/高度,'$ Width' /'$ Height'和'$ FinalWidth' /'$ FinalHeight'的真实世界值吗? – maxhb

回答

4

我想这是你想要的东西:

<?php 
    $square=500; 

    // Load up the original image 
    $src = imagecreatefrompng('original.png'); 
    $w = imagesx($src); // image width 
    $h = imagesy($src); // image height 
    printf("Orig: %dx%d\n",$w,$h); 

    // Create output canvas and fill with white 
    $final = imagecreatetruecolor($square,$square); 
    $bg_color = imagecolorallocate ($final, 255, 255, 255); 
    imagefill($final, 0, 0, $bg_color); 

    // Check if portrait or landscape 
    if($h>=$w){ 
     // Portrait, i.e. tall image 
     $newh=$square; 
     $neww=intval($square*$w/$h); 
     printf("New: %dx%d\n",$neww,$newh); 
     // Resize and composite original image onto output canvas 
     imagecopyresampled(
     $final, $src, 
     intval(($square-$neww)/2),0, 
     0,0, 
     $neww, $newh, 
     $w, $h); 
    } else { 
     // Landscape, i.e. wide image 
     $neww=$square; 
     $newh=intval($square*$h/$w); 
     printf("New: %dx%d\n",$neww,$newh); 
     imagecopyresampled(
     $final, $src, 
     0,intval(($square-$newh)/2), 
     0,0, 
     $neww, $newh, 
     $w, $h); 
    } 

    // Write result 
    imagepng($final,"result.png"); 
?> 

还要注意,如果你想缩小为300x600以适应500×500,同时保持纵横比,你会得到250x500不是200×500 。

+0

这适用于垂直站立的图像。但是如果我将图像水平放置,则图像会垂直“挤压”。 – odannyc

+0

好吧,我现在不在我的电脑上,但是现在你的白色背景尺寸合适,所以代码是正确的,直到'imagecopyresampled()',是吗?因此,我们需要获得原始图像的宽度和高度,并找出哪个更长,这很容易,然后我们相应地更改'imagecopyresampled()'的第2到第8个参数。如果你没有解决问题,我明天就会做。 –

+0

请再试一次。 –