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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制