Resize Multiple Images in a Folder using PHP

Sometimes we need to resize multiple images in a folder, using PHP script we can achieve just that. Just point to folder where your images are located and execute following PHP script to resize your images.

Modify source and destination folder location on top of script, you can also set width and height of Images. All resized images will be proportional. I have re-sized 300 images with this script, each 2-3 MB and took me about 8/10 minutes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php
//Maximize script execution time
ini_set('max_execution_time', 0);

//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory    = '/home/public_html/websites/images/'; //Source Image Directory End with Slash
$DestImagesDirectory    = '/home/public_html/websites/images/new/'; //Destination Image Directory End with Slash
$NewImageWidth      = 500; //New Width of Image
$NewImageHeight     = 500; // New Height of Image
$Quality        = 80; //Image Quality

//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImagesDirectory)){
    while(($file = readdir($dir))!== false){

        $imagePath = $ImagesDirectory.$file;
        $destPath = $DestImagesDirectory.$file;
        $checkValidImage = @getimagesize($imagePath);

        if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
        {
            //Image looks valid, resize.
            if(resizeImage($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality))
            {
                echo $file.' resize Success!<br />';
                /*
                Now Image is resized, may be save information in database?
                */


            }else{
                echo $file.' resize Failed!<br />';
            }
        }
    }
    closedir($dir);
}

//Function that resizes image.
function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
    list($iWidth,$iHeight,$type)    = getimagesize($SrcImage);
    $ImageScale             = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
    $NewWidth               = ceil($ImageScale*$iWidth);
    $NewHeight              = ceil($ImageScale*$iHeight);
    $NewCanves              = imagecreatetruecolor($NewWidth, $NewHeight);

    switch(strtolower(image_type_to_mime_type($type)))
    {
        case 'image/jpeg':
            $NewImage = imagecreatefromjpeg($SrcImage);
            break;
        case 'image/png':
            $NewImage = imagecreatefrompng($SrcImage);
            break;
        case 'image/gif':
            $NewImage = imagecreatefromgif($SrcImage);
            break;
        default:
            return false;
    }

    // Resize Image
    if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
    {
        // copy file
        if(imagejpeg($NewCanves,$DestImage,$Quality))
        {
            imagedestroy($NewCanves);
            return true;
        }
    }
}

?>

33 Comments Add Comment

  • Any chance of making the script to work only on images wider than 800px? The way it’s working now it resizes all of them, makes image with width of 150px to 800, and i need only the large images to be resized.

     Reply
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    case 'image/jpeg':
    $NewImage = imagecreatefromjpeg($SrcImage);
    break;
    case 'image/png':
    $NewImage = imagecreatefrompng($SrcImage);
    break;
    case 'image/gif':
    $NewImage = imagecreatefromgif($SrcImage);
    break;
    default:
    return false;

    this worked for me for all the files. need to add break condition in every case

     Reply
  • Hey

    Thank you so much you saved my time bro :)

    I have a problem with this code .

    This code successfully converted JPEG files but all PNG file failed to convert .

    Can you tell me about this trouble ?

    Please let me know your answer with email .

    Thanks alot

     Reply
  • Great Script, Thanks a ton!!

     Reply
  • I must be stupid. I cant find where to download the complete script. :)

     Reply
  • Hi,

    is it possible that the code is broken ? There seems to be something missing…or did I just oversaw the download for the actual php file somewhere ?

    Best regards
    HyperPac

     Reply
  • good code :). thank you

     Reply
  • I had over 100 jpegs to resize. I copied the script to a file, changed the directories, put new width and heights in, and ran it. Bang! Done!

     Reply
  • Great script, I have it working in all respects. Would there be a chance of amending it to include an imageconvolution matrix to sharpen the images once resized? I would really appreciate this. thanks!

     Reply
  • Hi there,
    You can replace the switch statement with this :

    switch(strtolower(image_type_to_mime_type($type)))
    {
    case ‘image/jpeg’:
    $NewImage = imagecreatefromjpeg($SrcImage);
    break;
    case ‘image/png’:
    $NewImage = imagecreatefrompng($SrcImage);
    break;
    case ‘image/gif’:
    $NewImage = imagecreatefromgif($SrcImage);
    break;
    default:
    return false;
    }

    Hope this helps.

     Reply
  • I got this warning:

    Warning: imagejpeg(C:/Users/user/Pictures/godrej/new/abcd2-thumb.jpg): failed to open stream: No such file or directory in C:\wamp\www\Demo\resizeimg.php on line 62

     Reply
    • I think WAMP has the same settings as Apache, it won’t go above your /www folder. So when you call file from your pictures, you’re getting a permission error.
      Try putting the image inside /www/Demo and calling it relatively to the script.
      example: create folder /www/Demo/imgaes
      path: /images/1.jpg

  • Warning: imagejpeg(C:/Users/user/Pictures/godrej/new/abcd2-thumb.jpg): failed to open stream: No such file or directory in C:\wamp\www\Demo\resizeimg.php on line 62

     Reply
  • How can I resize all the pictures in the folder but in subfolder too w/ this script. Thank you!!!

     Reply
  • [function.opendir]: failed to open dir: not implemented in /home/content/94/11055294/html/test/user-content/uploads/resize.php on line 13

     Reply
  • This script works for me on my localhost with wamp installed. But it doesn’t work when i upload the script to the server. Why does it do that?

     Reply
  • thanks for good resize

    i want ask how do that in same folder ? i want work in one folder (Source) only and apply resize on same folder …

     Reply
    • Easy! just make your $ImagesDirectory and the $DestImagesDirectory the same… like so:
      $ImagesDirectory = ‘/home/public_html/websites/images/’;
      $DestImagesDirectory = ‘/home/public_html/websites/images/’;

      WARNING though… it’ll rewrite your original files.

    • i try it that but Did not succeed

  • Hi I would like to ask how to make it resize only the photos which are not resized yet.. so that it won’t loop to resize the already resized photos?

     Reply
    • You can’t. This code opens the directory and goes through all the files in it. In case the image matches the size, no changes will be made.

      To do what you’re asking, you’ll have to make it a function, and call it for individual images. Something like this: (give it source – destination, and the width – height that you want)

      <?php
      function resize($source,$destination,$newWidth,$newHeight)
      {
      //Maximize script execution time
      ini_set('max_execution_time', 0);

      //Initial settings, Just specify Source and Destination Image folder.
      $ImagesDirectory = $source; //Source Image Directory End with Slash
      $DestImagesDirectory = $destination; //Destination Image Directory End with Slash
      $NewImageWidth = $newWidth; //New Width of Image
      $NewImageHeight = $newHeight; // New Height of Image
      $Quality = 90; //Image Quality

      $imagePath = $ImagesDirectory;
      $destPath = $DestImagesDirectory;
      $checkValidImage = @getimagesize($imagePath);

      if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
      {
      //Image looks valid, resize.
      if(resizeImage($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality))
      echo $file.' resize Successful!’;
      else
      echo $file.’ resize Failed!’;
      }
      }

      //Function that resizes image.
      function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
      {
      list($iWidth,$iHeight,$type) = getimagesize($SrcImage);
      $ImageScale = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
      $NewWidth = ceil($ImageScale*$iWidth);
      $NewHeight = ceil($ImageScale*$iHeight);
      $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);

      switch(strtolower(image_type_to_mime_type($type)))
      {
      case ‘image/jpeg’:
      case ‘image/png’:
      case ‘image/gif’:
      $NewImage = imagecreatefromjpeg($SrcImage);
      break;
      default:
      return false;
      }

      // Resize Image
      if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
      {
      // copy file
      if(imagejpeg($NewCanves,$DestImage,$Quality))
      {
      imagedestroy($NewCanves);
      return true;
      }
      }
      }
      ?>

    • Sorry for ugly looking code! Damn comment took out all my indentations :(

  • Great Code!
    Very customizable, thanks a lot :)

     Reply
  • Great code and works a treat but …
    How can I make it so that it only resizes pictures above a certain size of width?
    Regards

     Reply
  • Thank you. it perfectly work for me!

     Reply
  • This script works perfectly fine for me on my localhost. I am running a wamp server installation on my localhost, and it works fine. But when i try uploading the script to my server, for some reason its not working. Can someone tell me what could be the issue? Thanks.

     Reply
  • Thank you for this wonderful script – is there an easy way to delete the source image once the new one is created?

     Reply
  • Saran Chamling Thank you very much for very useful post, I just used it successfully.

    For those who want to re-size .png images replace,

    1
    $NewImage = imagecreatefromjpeg($SrcImage);

    and use the following function,

    1
    $NewImage = imagecreatefrompng($SrcImage);
     Reply
  • Love the script. Question though. How can it be implemented to resize images and also create an icon of the image? :D

     Reply
  • Alexandre Broggio

    Thanks for script

     Reply