Resizing image using php

Creating directories( folders ) for the application

  1. Create a directory named myWebApp in your server root directory eg. in www directory (for windows).
  2. Create subdirectories named css and myServer inside your myWebApp directory.
  3. Create a subdirectory named resizedImages inside your myServer directory. Here all the resized images will be stored.

HTML markup

<!DOCTYPE html>
        <title>Resizing image using PHP</title>
        <link rel="stylesheet" href="css/my_styles.css">

        <form method="post" action="myServer/resize_image.php" id="myForm" enctype="multipart/form-data" required="required">
            <div class="label">Pick a jpg on png image</div>
            <input type="file" name="img" accept="image/jpeg,image/png" required="required">
            <div class="label">New width &amp; new height</div>
            <div id="tb">
                <div class="td" id="w">
                    <input type="number" name="new_width" placeholder="New width">
                <div class="td" id="h">
                    <input type="number" name="new_height" placeholder="New height">
            <input type="submit" value="Submit form">

Save this html as image_picker.html file in myWebApp directory.

CSS rules



    margin:0 auto;
    padding:0px 20px 20px 20px;
    border:1px solid #af111c;

    display: block;
    padding: 10px;
    color: #fff;
    background-color: #af111c;
    text-align: center;

    border-bottom:1px solid #ccc;

    padding:20px 0px;





Save this css as my_styles.css file in css directory.

PHP code

php.ini file directives required for this application.

Set the following directives to appropriate values in your php.ini file.

  1. file_uploads must be set to On.
  2. upload_max_filesize must be greater than the size of image that you are uploading.
    i.e if you are uploading an image of size 10M(Mega bytes) then upload_max_filesize value must be greater than 10M eg. 11M
  3. post_max_size should be greater than upload_max_filesize value.
  4. memory_limit must be set to appropriate value (Needed in case when there is Fatal error: Allowed memory size of ******** bytes exhausted while processing the image). But memory limit should not be set to a high number as this may affect the execution of other functionalities of server.
    $image = $_FILES['img'];

    // 1. Check if image is provided or not
    if( empty($image['tmp_name']) )

    // 2. Check if valid image is provided or not
    $size = getimagesize($image['tmp_name']);
    if( $size === false )
        // Invalid image
        echo 'Invalid image !';
        // Get width and height of uploaded image
        $dimensions = array($size[0],$size[1]); // array(image width, image height)

    // 3. Now check type of uploaded image [ jpg and png only ]
    // Checking file type based on content of image
    $fileType = exif_imagetype($image['tmp_name']);
    $allowedTypes = array(IMAGETYPE_PNG,IMAGETYPE_JPEG);

    if( !in_array($fileType,$allowedTypes) )
        // File type not supported
        echo 'File type not supported ! try jpg or png image.';
        // Set the image file extension
        if($fileType == IMAGETYPE_JPEG) // JPG image
            $extension = '.jpg';
        else // PNG image
            $extension = '.png';

    // 4. Create file name
    $fileName = SHA1(time().mt_rand(0,20000).$image['name']);

    // 5. Path to store resized images
    $path = 'resizedImages'.DIRECTORY_SEPARATOR.$fileName.$extension;

    // 6. Resizing the image
    $imgContent = file_get_contents($image['tmp_name']); // Get content of the uploaded image file

    $old_image = imagecreatefromstring($imgContent);
    $old_width = $dimensions[0];
    $old_height = $dimensions[1];

    $ratio = $old_width / $old_height;

    // 7. Get new width and height for the image
    $new_width = (int)trim($_POST['new_width']); // New width
    $new_height = (int)trim($_POST['new_height']); // New height

    if( !empty($new_width) && empty($new_height) ) // If only new width is provided
        if( !is_integer($new_width) || $new_width <= 0 )

        // Set the new height maintaining width:height ratio of image
        $new_height = $new_width / $ratio;
    else if( empty($new_width) && !empty($new_height) ) // If only new height is provided
        if( !is_integer($new_height) || $new_height <= 0 )

        // Set the new width maintaining width:height ratio of image
        $new_width = $new_height * $ratio;
    else if( empty($new_width) && empty($new_height) )
        // If new width and new height are not provided then use dimensions of uploaded image
        $new_width = $old_width;
        $new_height = $old_height;

    // 8. Create a new image with the new dimensions ( default background color is black )
    $new_image = imagecreatetruecolor($new_width,$new_height);
    if( $new_image === false ) // Could not create new image

    // 9. Setting the background color of new image ( created in previous step )
    if( $fileType == IMAGETYPE_JPEG ) // JPG image
        // Make the black background to white
        $bg = imagecolorallocate($new_image,255,255,255);
        // 255,255,255 is RGB code for white color
    else // PNG image
        // Make the black background to transparent
        $alpha = imagesavealpha($new_image, true);
        $bg = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
        // Last parameter is alpha value, it's value is set to 127 means full transparency

    $filled = imagefill($new_image,0,0,$bg); // paint the new image with new background color 

    // 10. Copy old image to new image

    // 0,0,0,0 in above function parameters are x-coordinate of new image, y-coordinate of new image, x-coordinate of old image, y-coordinate of old image respectively. 

    // These coordinates means that -> Copy content from (0,0) coordinates of old image and start pasting it from (0,0) coordinates in the new image.

    // 11. Save the new resized image file to the "processed_images" directory
    if( $fileType == IMAGETYPE_JPEG ) // JPG image
    else // PNG image

    // 12. Free any memory associated with the new image

    echo "<a href='$path' target='_blank'>View the image</a>";

Save this php code as resize_image.php file in myServer directory.

Execution of the application

  1. Start your wamp / lamp / xampp server.
  2. Open image_picker.html HTML file in your web browser.
  3. Select an image file and provide the dimensions.
  4. If only width or height is provided, image will be resized maintaining the width:height ratio.
  5. If both width & height are provided then resized image will have the exact provided dimensions.
  6. If nothing is provided then the output image will have the exact dimensions of the original image.
  7. Submit the form.
  8. Go to resizedImages directory ( inside myServer directory ) there you will find your resized images.

Plus point

If no width & and height are provided then the size of output image may reduce to a lower or greater extent depending on the image ( above PHP code also works as image size reducer ), but for some images size may increase.


If you dont’t have access to exif_imagetype() function ( as this may be the case with some web-hosting providers ) then you can use pathinfo() function to get the image extension.

$extension = pathinfo($_FILES['img']['name'],PATHINFO_EXTENSION); 
// If jpg image is uploaded then <b>$extension</b> will have value jpg, and png in case of png image.

For further readings check out these links

Read more about pathinfo() function

Read more about GD and Image functions in PHP

Leave a Reply