dongningwen1146 2014-09-26 11:11
浏览 53
已采纳

添加黑条以创建16x9图像

I have a jpg on my server. I use

imagecreatefromjpeg($imgPath);

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

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!

  • 写回答

1条回答 默认 最新

  • dongyi9023 2014-09-26 11:27
    关注

    This will do the trick:

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

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vc6.0中想运行代码的时候总是提示无法打开文件是怎么回事
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题