【问题标题】:Resize an image and fill gaps of proportions with a color调整图像大小并用颜色填充比例间隙
【发布时间】:2010-06-16 05:41:25
【问题描述】:

我正在将徽标上传到我的系统,它们需要在 60x60 像素的框中进行修复。我有所有代码来按比例调整它,这不是问题。

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

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

我会发布我的代码,但它很长,但如果有要求我可以发布。

有谁知道如何做到这一点,或者你能指出我这样做的代码/教程吗?

【问题讨论】:

    标签: php image gd image-manipulation


    【解决方案1】:

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

    【讨论】:

    • 完美——谢谢:)。我现在遇到的唯一问题是,我确信我可以弄清楚颜色并不总是变成白色。
    • 干得好,SO 上提供的很多解决方案最终都会生成黑色矩形。不是这个:)
    【解决方案2】:

    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

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

    接下来是。

    【讨论】:

      猜你喜欢
      • 2016-05-19
      • 1970-01-01
      • 2011-07-15
      • 2012-12-15
      • 2018-05-10
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多