上传前如何调整图像大小

时间:2019-05-01 03:06:11

标签: php image image-resizing

我正在尝试在上传之前调整图像大小。我在下面的代码中添加了$img = resize_image($_FILES['Image']['tmp_name'], 200, 200);行。该代码可以正常上传。现在,我只是尝试调整图像的大小。我不确定如何获取返回值$ img并将其保存在move_uploaded_file中。尝试将$_FILES['Image']['tmp_name]替换为$img时,出现解析错误。我还添加了resize_image函数,以便您可以看到它究竟返回了什么。

    {
            $image_name= $_FILES['Image']['name'];
            $img = resize_image($_FILES['Image']['tmp_name'], 200, 200);
        $image_name =  $picCounter .$firstName .$image_name;
        move_uploaded_file( $_FILES['Image']['tmp_name'], "IMG/$image_name");
        correctImageOrientation("IMG/$image_name");

        $image_path = "/IMG/" .$image_name;

        $picCounter = $picCounter++;
        $sql = ("UPDATE LoginInformation SET PicCounter = PicCounter + 1 WHERE Email = '" . $useremail . "'" );
        mysqli_query($conn, $sql);
    }
    else
    {
        $image_path = "/IMG/square-image.png";
    }

这是调整大小功能

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

1 个答案:

答案 0 :(得分:1)

您无法在使用PHP上传之前调整图片大小,PHP是服务器端语言,并且仅在上传图片之后才有效。

您需要通过JavaScript进行此操作。 看到这个: Use HTML5 to resize an image before upload