dqbh8054 2017-03-18 13:27
浏览 118
已采纳

PHP图像使用宽高比调整大小

I have this PHP script that resizes an image to 50% (or any preset percentage)

  1. $filename = 'test.jpg';
  2. $percent = 0.5;
  3. // Content type
  4. header('Content-Type: image/jpeg');
  5. // Get new dimensions
  6. list($width, $height) = getimagesize($filename);
  7. $new_width = $width * $percent;
  8. $new_height = $height * $percent;
  9. // Resample
  10. $image_p = imagecreatetruecolor($new_width, $new_height);
  11. $image = imagecreatefromjpeg($filename);
  12. imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  13. // Output
  14. imagejpeg($image_p, null, 100);

Now what if I want to specify $new_width as 1200 (px) and tell the $new_height to be calculated automatically keeping the aspect ratio and set the name of the new image as "test-2.jpg"

  1. $filename = 'test.jpg';
  2. // Content type
  3. header('Content-Type: image/jpeg');
  4. // Get new dimensions
  5. list($width, $height) = getimagesize($filename);
  6. $new_width = 1200;
  7. $new_height = // MUST BE AUTO;
  8. // Resample
  9. $image_p = imagecreatetruecolor($new_width, $new_height);
  10. $image = imagecreatefromjpeg($filename);
  11. imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  12. // Output
  13. imagejpeg($image_p, null, 100);

展开全部

  • 写回答

2条回答 默认 最新

  • dro60731 2017-03-18 13:33
    关注

    "Keep aspect ratio" means that the following equation must hold:

    $new_height / $new_width == $height / $width
    

    Thus, the equation for calculating the new height is:

    $new_height = ceil($height * ($new_width/$width));
    

    Note that ceil ensures that the new height is an integer value and at least 1 (given that new width and old width+height are all positive).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部