【问题标题】:Resize image - Keep proportion - Add white background调整图像大小 - 保持比例 - 添加白色背景
【发布时间】:2018-01-23 16:01:55
【问题描述】:

我想将图像调整为正方形。假设我想要一个 500x500 的平方图像,而我有一个 300x600 的图像 我想将该图像的大小调整为 200x500,然后为其添加白色背景以使其变为 500x500

这样做我得到了一些好处:

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

它几乎做对了所有事情。图片居中和一切。除了背景是黑色而不是白色:/

有人知道我做错了什么吗?

【问题讨论】:

  • 据我所知,PHP 无法做到这一点。
  • 您可能想要使用像imagemagick 这样的扩展名。特别是如果其他额外的图像处理即将出现。
  • 您能否提供原始图像宽度/高度的真实值,$Width/$Height$FinalWidth/$FinalHeight

标签: php image gd


【解决方案1】:

我想这就是你想要的:

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

另请注意,如果您想缩小 300x600 以适应 500x500,同时保持纵横比,您将获得 250x500 而不是 200x500。

【讨论】:

  • 这适用于垂直站立的图像。但是,如果我将图像水平放置,图像会垂直“压扁”。
  • 好吧,我现在不在我的电脑前,但是你现在有一个大小合适的白色背景,所以代码在 imagecopyresampled() 之前是正确的,是吗?所以我们需要得到原图的宽高,找出哪个长一些,这很容易,然后我们只需相应地改变imagecopyresampled()的第2-8个参数。如果你不解决,我明天再做。
  • 请再试一次。
  • 虽然它有效,但它比必要的复杂得多。除了 if-else,您可以简单地计算 $width / $bitmap_width 比率、$height / $bitmap_height 比率,获取两者中的最小值并使用该比例调用 imagecopyresampled。这将立即为您提供“适合”尺寸。而且,实际上,如果您改用最大值,您可以通过相同的操作获得“填充到”大小。
猜你喜欢
  • 2017-11-06
  • 2017-08-24
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
相关资源
最近更新 更多