Resizing Image Using PHP

Image resizing is one of the most common functions performed on any website. Various images are needed to be resized or cropped or converted into thumbnails and stored before showing them on the website.

PHP provides some of the most sophisticated functions for image manipulation.

The code below describes how to resize an uploaded image. In this code,

  1. The image is uploaded first
  2. Then the file is checked for correct size (less than 50kb here).
  3. The image type is checked (jpeg, png and gif images allowed).
  4. Then we get the size that is height and width of the image.
  5. Next, we set the indices for image resizing. The destination folder maximum image height/width, quality and resized image name.
  6. All these parameters are passed to the resizeimage function which actually does the resizing of the image.

There are two files, index.php where the file is uploaded and img-action.php where all the processing is done.

index.php

<h2>Image Resizer</h2>

<form enctype="multipart/form-data" action="img-action.php" method="post" >

    <label for="file">Image</label>
    <input type="file" name="file" id="file" required />


    <br><br>
    <input type="submit" value="Submit" />

</form>

img-action.php

<?php

function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0) 
        {   return false;
        }

    //Construct a proportional size of new image
    $ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight); 
    $NewWidth       = ceil($ImageScale*$CurWidth);
    $NewHeight      = ceil($ImageScale*$CurHeight);

    if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
        {   $NewWidth = $CurWidth;
            $NewHeight = $CurHeight;
        }
    $NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight);
    // Resize Image
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
        {   switch(strtolower($ImageType))
                {   case 'image/png':
                        imagepng($NewCanves,$DestFolder);
                        break;
                    case 'image/gif':
                        imagegif($NewCanves,$DestFolder);
                        break;          
                    case 'image/jpeg':
                    case 'image/pjpeg':
                        imagejpeg($NewCanves,$DestFolder,$Quality);
                        break;
                    default:
                        return false;
                }
            if(is_resource($NewCanves)) 
                { imagedestroy($NewCanves); 
                } 
            return true;
        }

}


if(isset($_FILES['file']['name'])){

    if( $_FILES['file']['size']<50000 ){


            //Some Settings
            $BigImageMaxSize                = 300; //Image Maximum height or width
            $ResizePrefix                   = "resized_"; //Normal resize Prefix
            $OriginalDestinationDirectory   = 'original/';
            $ResizedDestinationDirectory    = 'resized/'; //Upload Directory ends with / (slash)
            $Quality                        = 100;
            $ResizedImageLocation[]         = "";
            $OriginalImageLocation[]        = "";

            // some information about image we need later.
            $ImageName=$_FILES['file']["name"];
            $ImageSize=$_FILES['file']['size'];
            $TempSrc=$_FILES['file']['tmp_name'];
            $ImageType=$_FILES['file']['type'];

            $processImage = true;


            //Validate file + create image from uploaded file.
                    switch(strtolower($ImageType))
                        {       case 'image/png':
                                    $CreatedImage = imagecreatefrompng($TempSrc);
                                    break;
                                case 'image/gif':
                                    $CreatedImage = imagecreatefromgif($TempSrc);
                                    break;
                                case 'image/jpeg':
                                case 'image/pjpeg':
                                    $CreatedImage = imagecreatefromjpeg($TempSrc);
                                    break;
                                default:
                                    $processImage = false; //image format is not supported!
                        }

                    //get Image Size
                    list($CurWidth,$CurHeight) = getimagesize($TempSrc);

                    //Set the Destination Image path
                    $DestRandImageName          = $ResizedDestinationDirectory.$ResizePrefix.$ImageName; //Name for Big Image
                    $OriginalImageName          = $OriginalDestinationDirectory.$ImageName; // Original Image Name

                    $moveImage = move_uploaded_file($TempSrc, $OriginalImageName);

                    //Resize image to our Specified Size by calling resizeImage function.
                    if($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
                        {   

                            //Get New Image Size
                            list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
                            $ResizedImageLocation   = $DestRandImageName;
                            $OriginalImageLocation  = $OriginalImageName;

                            echo 'You can view your images here<br>

                            <p><a href="'.$OriginalImageLocation.'" target="_blank">Original Image</a></p>
                            <p><a href="'.$ResizedImageLocation.'" target="_blank">Resized Image (resized to maximum height/width 300px)</a> <br> Images having both height/width less than 300px not resized</p>

                            ';


                        }
                    else
                        {   echo '<p style="color:red;">Error occurred while trying to process <strong>'.$ImageName.'</strong>! Please check if file is supported</div>'; //output error
                        }

    }

    else{
        echo '<p style="color:red;">Please upload image of maximum size 50kb</p>';
    }

}

?>

Image after uploading the file

Original Image

Resized image

Please feel free to download the source code for reference.

View Demo Download source

This content has been helpful to you?

Thanks for contributing!

Yes No