dougong8012 2014-10-23 08:33
浏览 57
已采纳

在PHP中查找给定宽度保持比例的图像高度

I am trying to resize an image to a width of 500px. I want to keep the aspect ratio of the image.

My original image is

enter image description here

When I resized it to size of width 500, it is coming like enter image description here

I am doing the following code for resizing image.

$target_dir="uploads/reference/".$data['CP_Image'];
move_uploaded_file($tmp_file, $target_dir);
list($w, $h) = getimagesize($target_dir);
$width=500;
$ratio = $width / $h;
$x = ($w - $width / $ratio) / 2;
$height = 500 / $ratio;exit;

$path = "uploads/reference/".$data['CP_Image'];
$thumb = imagecreatetruecolor($width, $height);
$source = imagecreatefromjpeg($target_dir);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $width, $height, $w, $h);

// Output and free memory
imagejpeg($thumb,$path);
imagedestroy($thumb);

With this code, the width is changed to 500px but height is not proportional. What I am doing wrong? Can anyone help me to fix it?

Thanks in advance

  • 写回答

1条回答 默认 最新

  • douzhuican0041 2014-10-23 08:37
    关注

    You're calculating the ratio incorrectly. Instead of dividing the new width by the original height, you want something like this:

    list($w, $h) = getimagesize($target_dir);    
    $width = 500;
    $ratio = $w / $h;
    $height = $width / $ratio;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向