调整图像大小 - 保持比例 - 添加白色背景 [英] Resize image - Keep proportion - Add white background

查看:783
本文介绍了调整图像大小 - 保持比例 - 添加白色背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图片调整为正方形。假设我想要500x500的平方图像并且我有300x600
的图像我想将该图像调整为200x500,然后添加白色背景使其成为500x500

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?

< a href =https://i.stack.imgur.com/iKKwu.jpg =nofollow noreferrer>

推荐答案

我认为这就是你想要的:

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

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

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

这篇关于调整图像大小 - 保持比例 - 添加白色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆