Jay Smoke
Jay Smoke

Reputation: 604

How to auto resize uploaded image using php

I have a script;

        $fileName = $_FILES['userfile']['name'];
        $tmpName = $_FILES['userfile']['tmp_name'];
        $fileSize = $_FILES['userfile']['size'];
        $fileType = $_FILES['userfile']['type'];

        // get the file extension first
        $ext = substr(strrchr($fileName, "."), 1); 

        // make the random file name
        $randName = md5(rand() * time());

        // and now we have the unique file name for the upload file
        $filePath = $imagesDir . $randName . '.' . $ext;

        $result = move_uploaded_file($tmpName, $filePath);
        if (!$result) {
            echo "Error uploading file";
        exit;
    } 

if(!get_magic_quotes_gpc()) {

        $fileName = addslashes($fileName);
        $filePath = addslashes($filePath);

    }

which am using to upload images but I would like to add a script to resize the image to a specific size before it's uploaded. How do I do that???

Upvotes: 2

Views: 19686

Answers (2)

davidethell
davidethell

Reputation: 12048

EDIT: I have updated this to include your script elements. I'm starting from the point where you obtain your filename.

Here is a very quick, simple script to do it:

$result = move_uploaded_file($tmpName, $filePath);
$orig_image = imagecreatefromjpeg($filePath);
$image_info = getimagesize($filePath); 
$width_orig  = $image_info[0]; // current width as found in image file
$height_orig = $image_info[1]; // current height as found in image file
$width = 1024; // new image width
$height = 768; // new image height
$destination_image = imagecreatetruecolor($width, $height);
imagecopyresampled($destination_image, $orig_image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// This will just copy the new image over the original at the same filePath.
imagejpeg($destination_image, $filePath, 100);

Upvotes: 4

J_D
J_D

Reputation: 681

Well, you can't change the size of it before it's uploaded, but you can use the GD Library to change the size of it after it's on the server. Check out GD and Image Functions listing for all of the related functions for dealing with images.

There is also this tutorial that will show you a custom class for doing a resize, but unless you need the whole think you can focus on the function resize to see how it's done

Upvotes: 0

Related Questions