Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize image to maximum width or height in PHP without cropping

Tags:

php

I have an AJAX form that sends 4 pictures to and PHP form handler. The accepted formats are .gif, .png, .jpg or .jpeg. I am checking the image file type using javascript before sending the form.

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 will upload large image files and I want to automatically resize them to a maximum width/height without cropping the image. How can I do that using PHP?

like image 443
Andrei Răileanu Avatar asked Oct 29 '16 23:10

Andrei Răileanu


Video Answer


1 Answers

You can use php GD library for this. Inside your if condition after rename function 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);
like image 50
Rahman Ashik Avatar answered Oct 27 '22 01:10

Rahman Ashik