对上传的多张图片以相同比例调整大小 PHP

Resizing with same ratio on multiple images from upload PHP

我已经苦苦思索了好几个小时,但我终其一生都想不出如何使用简单的表单在上传时以相同的比例调整图像的大小。如果有人上传大于 2048px 水平或垂直的图像,我想将其调整为 2048px 的大小,然后将其保存在文件夹中。

因为我基本上只用我的表格从头开始,所以不幸的是我没有任何东西可以给你看,但主要是在搜索和阅读关于 GD 的内容,但对我不起作用......

非常感谢任何提示!

编辑:

if(isset($con, $_POST['save_button'])){
    // IMAGE PROCESSING
    $name = $_FILES['file_upload']['name'];
    $tmp_name = $_FILES['file_upload']['tmp_name'];
    $type = $_FILES['file_upload']['type'];
    $size = $_FILES['file_upload']['size'];
    $error = $_FILES['file_upload']['error'];

    move_uploaded_file($tmp_name, "social_images/$name.jpg");

    function resize_image($img, $w, $h, $crop=FALSE) {
        list($width, $height) = getimagesize($img);
        $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($img);
        $dst = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        return $dst;
    }

    $img = resize_image("social_images/$name.jpg", 780, 780);

    header("location: index.php");
    exit();
}

重新尝试并重新测试:

<?php
function shazam($file, $w, $h) {
    list($width, $height) = getimagesize($file);

    if ($width > $height) {
        $r = ($w / $width);
        $newwidth = $w;
        $newheight = ceil($height * $r);
    } 

    if ($width < $height) {
        $r = ($h / $height);
        $newheight = $h;
        $newwidth = ceil($width * $r);
    } 

    if ($width == $height) {
        $newheight = $h;
        $newwidth = $w;
    }

    $src = imagecreatefromjpeg($file);
    $tgt = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($tgt, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $tgt;
}

$img = shazam("thepicwithpath.jpg", 850, 850);
imagejpeg($img, "theresizedpicwithpath.jpg", 75);
?>

请注意最后的 imagejpeg() 是实际生成新文件的方法。