duanan5940 2013-01-04 21:36
浏览 7
已采纳

too long

I have an upload form where you select photos. Upon upload I resize the image if necessary.

It seems any photo that I upload where the HEIGHT > WIDTH stretches the image. If I upload an image where WIDTH > HEIGHT it works fine. I've been racking my brain trying to figure this out. I'm pretty sure I know which line is the issue and I've pointed it out in a comment.

Can anyone see what is wrong with my math? Thanks!

<?php
$maxWidth  = 900;
$maxHeight = 675;
$count     = 0;

foreach ($_FILES['photos']['name'] as $filename)
{
    $uniqueId   = uniqid();
    $target     = "../resources/images/projects/" . strtolower($uniqueId . "_" . $filename);
    $file       = $_FILES['photos']['tmp_name'][$count];    
    list($originalWidth, $originalHeight) = getimagesize($file);

    // if the image is larger than maxWidth or maxHeight
    if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
    {
        $ratio = $originalWidth / $originalHeight;

        // I think this is the problem line
        (($maxWidth / $maxHeight) > $ratio) ? $maxWidth = $maxWidth * $ratio : $maxHeight = $maxWidth / $ratio; 

        // resample and save
        $image_p    = imagecreatetruecolor($maxWidth, $maxHeight);
        $image      = imagecreatefromjpeg($file);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $maxWidth, $maxHeight, $originalWidth, $originalHeight);
        $image      = imagejpeg($image_p, $target, 75);
    }
    else
    {
        // just save the image
        move_uploaded_file($file,$target);
    }
    $count += 1;
}
?>
  • 写回答

1条回答 默认 最新

  • douerqu2319 2013-01-04 21:44
    关注

    When scaling, you need to modify both the width and the height of the target.

    Try:

    if ($originalWidth > $maxWidth || $originalHeight > $maxHeight)
    {
        if ($originalWidth / $maxWidth > $originalHeight / $maxHeight) {
            // width is the limiting factor
            $width = $maxWidth;
            $height = floor($width * $originalHeight / $originalWidth);
        } else { // height is the limiting factor
            $height = $maxHeight;
            $width = floor($height * $originalWidth / $originalHeight);
        }
        $image_p    = imagecreatetruecolor($width, $height);
        $image      = imagecreatefromjpeg($file);
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight);
        $image      = imagejpeg($image_p, $target, 75);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上