调整图像大小 - 保持比例 - 添加白色背景

I want to resize my images to a square. Say I want a squared image of 500x500 and I have an image of 300x600 I want to resize that image down to 200x500 and then add a white background to it to make it 500x500

I got something working good by doing this:

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

It's doing almost EVERYTHING right. The picture is centered and everything. Except the background is black and not white:/

Anyone know what I'm doing wrong?

picture

I think this is what you want:

<?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
",$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
",$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
",$neww,$newh);
      imagecopyresampled(
         $final, $src, 
         0,intval(($square-$newh)/2),
         0,0,
         $neww, $newh, 
         $w, $h);
   }

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

Note also, that if you want to scale down 300x600 to fit in 500x500 whilst maintaining aspect ratio, you will get 250x500 not 200x500.