调整图像大小并用颜色填充比例间隙 [英] Resize an image and fill gaps of proportions with a color

查看:323
本文介绍了调整图像大小并用颜色填充比例间隙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将徽标上传到我的系统,他们需要修复一个60x60像素的盒子。我有所有代码按比例调整大小,这不是问题。

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.

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

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

理论上我创建一个白色矩形,60x60,然后我复制图像并将其调整为60x38并将其放入我的白色矩形,从顶部开始11px(这相当于我需要的总填充的22px。

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?

推荐答案

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

这篇关于调整图像大小并用颜色填充比例间隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆