Resizing an image to its maximum width or height in PHP without cropping

I have an AJAX form that submits 4 images and a PHP form handler. Acceptable formats are .gif, .png, .jpg or .jpeg. Before submitting the form, I check the image file type using javascript.

Now, in PHP, I have this code:

    while($x <= 4) {
        $target_dir = "files/";
        $target_file = $target_dir . basename($_FILES["fileUpload".$x]["name"]);
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
        if (move_uploaded_file($_FILES["fileUpload".$x]["tmp_name"], $target_file)) {
                    $filename = date("d-m-Y---H-i-s---").rand(10000,99999);
                    $oldfile = $target_file;
                    $newfile = $target_dir . $filename . "." . $imageFileType;
                    rename($oldfile, $newfile);
                    $file[$x] = $filename . "." . $imageFileType;
                    $fileCounter++;
        }
      $x++;
    }

Some people upload large image files, and I want to automatically resize them to the maximum width / height without cropping the image. How to do it using PHP?

+4
source share
2 answers

You can use the php GD library for this. Inside your if condition, after renaming you can write this code:

list($width, $height) = getimagesize($file);
$ratio = $width / $height;
if( $ratio > 1) {
    $resized_width = 500; //suppose 500 is max width or height
    $resized_height = 500/$ratio;
}
else {
    $resized_width = 500*$ratio;
    $resized_height = 500;
}

    if ($imageFileType == 'png') {
        $image = imagecreatefrompng($newfile);
    } else if ($imageFileType == 'gif') {
        $image = imagecreatefromgif($newfile);
    } else {
        $image = imagecreatefromjpeg($newfile);
    }

$resized_image = imagecreatetruecolor($resized_width, $resized_height);
imagecopyresampled($resized_image, $image, 0, 0, 0, 0, $resized_width, $resized_height, $width, $height);
+3
source

gzip php,

if ($_FILES["fileToUpload"]["size"] > 500000)
0

Source: https://habr.com/ru/post/1659296/


All Articles