Resize an image and fill gaps of proportions with a color

廉价感情. 提交于 2019-12-03 09:00:47

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!