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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写