添加黑条以创建16x9图像 [英] Add black bars to create a 16x9 image

查看:85
本文介绍了添加黑条以创建16x9图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器上有一个jpg.我用

I have a jpg on my server. I use

imagecreatefromjpeg($imgPath);

将其打开.我想通过在顶部+底部或左侧+右侧添加黑条使其成为16x9图像. (想想background-size: contain; background-position: center;)这就是我所拥有的:

to open it. I want to make it a 16x9 image by adding black bars to either the top+bottom or left+right. (Think background-size: contain; background-position: center;) This is all I have:

$img_info = getimagesize($imgPath);

我知道我需要使用ImageCreateTrueColor来制作空白图像,使用imagecopyresampled来创建图像,并使用imagejpeg来保存它.但是我不知道如何将它们放在一起.谢谢!

I know I need to use ImageCreateTrueColor to make the blank image, imagecopyresampled to create the image, and imagejpeg to save it. But I have no idea how to put them together. Thanks!

推荐答案

这可以解决问题:

$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,计算应放置原始图像的位置(中心对齐). 在给定位置复制原始图像 输出完成.

How it works: you create the $im container, and check for width and height. After this, the script checks which side is smaller than the other (multiplied / divided by the ratio) and adjust the output size. Calculate where the original image should be placed (center alignment) by dividing the difference between the original and the output image dimensions by 2. Copy over the original image at the given position Output, done.

这篇关于添加黑条以创建16x9图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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