Resize an image and fill gaps of proportions with a color

南楼画角 提交于 2019-12-04 15:52:24

问题


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 image becomes 60x38. The thing is, I need the picture to be 60x60, meaning I want to pad the top and bottom with white each (I can fill the rectangle with the color).

The theory is I create a white rectangle, 60x60, then I copy the image and resize it to 60x38 and put it in my white rectangle, starting 11px from the top (which adds up to the 22px of total padding that I need.

I would post my code but it's decently long, though I can if requested.

Does anyone know how to do this or can you point me to code/tutorial that does this?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/3050952/resize-an-image-and-fill-gaps-of-proportions-with-a-color

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