Resize image - Keep proportion - Add white background

你。 提交于 2019-12-11 13:25:40

问题


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?


回答1:


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\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");
?>

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



来源:https://stackoverflow.com/questions/35301104/resize-image-keep-proportion-add-white-background

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