我的服务器上有一张jpg。我用
imagecreatefromjpeg($imgPath);
打开它。我想通过在顶部+底部或左侧+右侧添加黑条来使其成为 16x9 图像。 (思考background-size: contain; background-position: center;
)这就是我所拥有的:
$img_info = getimagesize($imgPath);
我知道我需要使用ImageCreateTrueColor
制作空白图像,imagecopyresampled
创建图像,并且imagejpeg
来保存它。但我不知道如何将它们放在一起。谢谢!
这就能解决问题:
$im=imagecreatefromjpeg ($imgPath);
$width=ImageSX($im); $height=ImageSY($im); $ratio=16/9;
$width_out=$width; $height_out=$height;
if ($height_out*$ratio<$width_out) {$height_out=floor($width_out/$ratio);} else {$width_out=floor($height_out*$ratio);}
$left=round(($width_out-$width)/2);
$top=round(($height_out-$height)/2);
$image_out = imagecreatetruecolor($width_out,$height_out);
$bg_color = ImageColorAllocate ($image_out, 0, 0, 0);
imagefill($image_out,0,0,$bg_color);
imagecopy($image_out, $im, $left, $top, 0, 0, $width,$height);
imagejpeg($image_out);
它是如何工作的:创建 $im 容器,并检查宽度和高度。
之后,脚本检查哪一侧小于另一侧(乘以/除以比率)并调整输出大小。
通过将原始图像和输出图像尺寸之间的差异除以 2 来计算原始图像应放置的位置(中心对齐)。
在给定位置复制原始图像
输出,完成。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)