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 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信