2014-09-26 99 views
1

我的服务器上有一个jpg文件。我用添加黑条以创建16x9图像

imagecreatefromjpeg($imgPath); 

打开它。我想通过向顶部+底部或左侧+右侧添加黑条来将其制作为16x9图像。 (想想background-size: contain; background-position: center;)这是我的全部:

$img_info = getimagesize($imgPath); 

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

回答

1

这将这样的伎俩:

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