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 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同