doufen3563 2016-02-09 20:00
浏览 539
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • douwaif22244 2016-02-09 22:35
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题