Upload and resize image with PHP before storing in upload folder



We can not allow users to upload any files and any images to our server, we need to make rule, for example we don’t allow them to upload an image bigger than 1mb/2mb or image that its width is more than 512px.

Here with this script we can prevent users to upload excessive big files and images. So before we store their image in our server, we compress them to an appropriate size.

This one is index.php file, the main page:

<?php

include("compressimage.php");

?>

<!DOCTYPE html>
<html>
	<head>
		<title>Upload and resize image with PHP before storing in upload folder</title>
	</head>
	<body>
		<h1><a href="index.php">Upload and resize image with PHP before storing in upload folder</a></h1>
		<?php
		if(isset($_POST["uploadnow"])){
			$maxsize = 524288; //maximum size of allowed image being uploaded (around half MB)
			$maxwidth = 512; //maximum width of allowed image dimension in pixels
			if($_FILES["imageupload"]["size"] == 0){
				echo "Please try again.";
			}else{
				if($_FILES['imageupload']['error'] > 0) { 
					echo "Error during uploading new image, try again later."; 
				}
				
				$extsAllowed = array( 'jpg', 'jpeg', 'png' ); //allowed extensions
				$uploadedfile = $_FILES["imageupload"]["name"];
				$extension = pathinfo($uploadedfile, PATHINFO_EXTENSION);
				
				//if uploaded image is in one of allowed extensions/formats, then proceed to next steps
				if(in_array($extension, $extsAllowed) ) { 
					
					//generate random image file name
					$newppic = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 10);
					$name = "upload/" . $newppic .".". $extension;
					
					//if uploaded image is exceeding max size then compress it
					if(($_FILES['imageupload']['size'] >= $maxsize)){
						echo "Uploaded image size is greater than $maxsize.<br>";
						compressimage($_FILES['imageupload']['tmp_name'], "upload/" . $newppic .".". $extension, $maxwidth); // resize it to 512pixels width
					}else{
						//check if the uploaded image width in pixels is greater than maxwidth
						list($width, $height, $type, $attr) = getimagesize($_FILES['imageupload']['tmp_name']);
						if($width > $maxwidth){
							echo "Uploaded image width is greater than $maxwidth.<br>";
							compressimage($_FILES['imageupload']['tmp_name'], "upload/" . $newppic .".". $extension, $maxwidth); // resize it to 512pixels width
						}else{
							echo "This image is just nice.<br>";
							$result = move_uploaded_file($_FILES['imageupload']['tmp_name'], $name);
						}
					}
					echo "New image has been uploaded.";
					
				} else { 
					echo "Image file is not valid. Please try uploading another image."; 
				}
			}
		}else{
			?>
			
			<form method="post" enctype="multipart/form-data">
				<input type="file" name="imageupload" accept="image/*">
				<input type="submit" name = "uploadnow" value="Upload">
			</form>
			
			<?php
		}
		?>
	</body>
</html>

<?php

And this one is compressimage.php file that you must include:

<?php
// Link image type to correct image loader and saver
// - makes it easier to add additional types later on
// - makes the function easier to read
const IMAGE_HANDLERS = [
    IMAGETYPE_JPEG => [
        'load' => 'imagecreatefromjpeg',
        'save' => 'imagejpeg',
        'quality' => 100
    ],
    IMAGETYPE_PNG => [
        'load' => 'imagecreatefrompng',
        'save' => 'imagepng',
        'quality' => 0
    ],
    IMAGETYPE_GIF => [
        'load' => 'imagecreatefromgif',
        'save' => 'imagegif'
    ]
];

/**
 * @param $src - a valid file location
 * @param $dest - a valid file target
 * @param $targetWidth - desired output width
 * @param $targetHeight - desired output height or null
 */
function compressimage($src, $dest, $targetWidth, $targetHeight = null) {

    // 1. Load the image from the given $src
    // - see if the file actually exists
    // - check if it's of a valid image type
    // - load the image resource

    // get the type of the image
    // we need the type to determine the correct loader
    $type = exif_imagetype($src);

    // if no valid type or no handler found -> exit
    if (!$type || !IMAGE_HANDLERS[$type]) {
        return null;
    }

    // load the image with the correct loader
    $image = call_user_func(IMAGE_HANDLERS[$type]['load'], $src);

    // no image found at supplied location -> exit
    if (!$image) {
        return null;
    }


    // 2. Create a thumbnail and resize the loaded $image
    // - get the image dimensions
    // - define the output size appropriately
    // - create a thumbnail based on that size
    // - set alpha transparency for GIFs and PNGs
    // - draw the final thumbnail

    // get original image width and height
    $width = imagesx($image);
    $height = imagesy($image);

    // maintain aspect ratio when no height set
    if ($targetHeight == null) {

        // get width to height ratio
        $ratio = $width / $height;

        // if is portrait
        // use ratio to scale height to fit in square
        if ($width > $height) {
            $targetHeight = floor($targetWidth / $ratio);
        }
        // if is landscape
        // use ratio to scale width to fit in square
        else {
            $targetHeight = $targetWidth;
            $targetWidth = floor($targetWidth * $ratio);
        }
    }

    // create duplicate image based on calculated target size
    $thumbnail = imagecreatetruecolor($targetWidth, $targetHeight);

    // set transparency options for GIFs and PNGs
    if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {

        // make image transparent
        imagecolortransparent(
            $thumbnail,
            imagecolorallocate($thumbnail, 0, 0, 0)
        );

        // additional settings for PNGs
        if ($type == IMAGETYPE_PNG) {
            imagealphablending($thumbnail, false);
            imagesavealpha($thumbnail, true);
        }
    }

    // copy entire source image to duplicate image and resize
    imagecopyresampled(
        $thumbnail,
        $image,
        0, 0, 0, 0,
        $targetWidth, $targetHeight,
        $width, $height
    );


    // 3. Save the $thumbnail to disk
    // - call the correct save method
    // - set the correct quality level

    // save the duplicate version of the image to disk
    return call_user_func(
        IMAGE_HANDLERS[$type]['save'],
        $thumbnail,
        $dest,
        IMAGE_HANDLERS[$type]['quality']
    );
}
?>

To get the complete source files, click this link:

https://github.com/habibieamrullah/PHPUploadAndResizeImage

loading...

Leave a Reply

Your email address will not be published.