Resize an image and fill gaps of proportions with a color

前端 未结 2 1687
一整个雨季
一整个雨季 2021-02-11 02:51

I am uploading logos to my system, and they need to fix in a 60x60 pixel box. I have all the code to resize it proportionately, and that\'s not a problem.

My 454x292px i

相关标签:
2条回答
  • 2021-02-11 03:04

    With 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);
    
    0 讨论(0)
  • 2021-02-11 03:16

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

    That's basically the function you want to copy and resize it smoothly.

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

    With that one you create a new black image.

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

    That part explains how to fill it white.

    The rest follows.

    0 讨论(0)
提交回复
热议问题