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

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

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

$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
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"

$filename = 'test.jpg';

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = 1200;
$new_height = // MUST BE AUTO;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
  • 写回答

2条回答 默认 最新

  • dro60731 2017-03-18 21: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条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了