Resize an image and fill gaps of proportions with a color

前端 未结 2 1686
一整个雨季
一整个雨季 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);
    

提交回复
热议问题