代码之家  ›  专栏  ›  技术社区  ›  Kerry Jones

调整图像大小并用颜色填充比例间隙

  •  2
  • Kerry Jones  · 技术社区  · 15 年前

    我正在将徽标上载到我的系统,它们需要固定在一个60x60像素的框中。我有所有的代码来按比例调整大小,这不是问题。

    我的454x292px图像变为60x38。问题是,我需要图片是60x60,这意味着我要用白色填充顶部和底部(我可以用颜色填充矩形)。

    理论是我创建一个白色矩形60x60,然后复制图像并将其大小调整为60x38,然后将其放入白色矩形中,从顶部开始11像素(加起来就是我需要的总填充量的22像素)。

    我会发布我的代码,但是它相当长,如果有要求的话我可以。

    有人知道怎么做吗?或者你能给我指代码/教程吗?

    2 回复  |  直到 9 年前
        1
  •  7
  •   user180100    9 年前

    GD:

    $newWidth = 60;
    $newHeight = 60;
    $img = getimagesize($filename);
    $width = $img[0];
    $height = $img[1];
    $old = imagecreatefromjpeg($filename); // change according to your source type
    $new = imagecreatetruecolor($newWidth, $newHeight)
    $white = imagecolorallocate($new, 255, 255, 255);
    imagefill($new, 0, 0, $white);
    
    if (($width / $height) >= ($newWidth / $newHeight)) {
        // by width
        $nw = $newWidth;
        $nh = $height * ($newWidth / $width);
        $nx = 0;
        $ny = round(fabs($newHeight - $nh) / 2);
    } else {
        // by height
        $nw = $width * ($newHeight / $height);
        $nh = $newHeight;
        $nx = round(fabs($newWidth - $nw) / 2);
        $ny = 0;
    }
    
    imagecopyresized($new, $old, $nx, $ny, 0, 0, $nw, $nh, $width, $height);
    // do something with new: like imagepng($new, ...);
    imagedestroy($new);
    imagedestroy($old);
    
        2
  •  0
  •   Zorf    15 年前

    http://php.net/manual/en/function.imagecopyresampled.php

    这基本上就是您想要平滑地复制和调整其大小的函数。

    http://www.php.net/manual/en/function.imagecreatetruecolor.php

    用这个你可以创建一个新的黑色图像。

    http://www.php.net/manual/en/function.imagefill.php

    这部分解释了如何将其填充为白色。

    剩下的就跟着。

    推荐文章