Resize images with PHP script

Did you ever try to resize many images at once? I did, and I wrote PHP script for that purpose. Anyway, after I selected few images from my photo album, I realized that every image was about 500KB and resolution of 1600×1200. This seems too big. Images should be smaller and lighter for upload. Is GIMP capable to resize all images inside directory – I don’t know, but opening, resizing and saving every image, will certainly take some time.

This small command line PHP script will help you to resize all JPG images inside current directory. Yes, you will find a lot of solutions with BASH scripts, but I decided to write my own command line PHP script. I didn’t want to use GD PHP functions for image processing. Instead of GD library, I used utilities from ImageMagick suite of tools: identify and convert. This way, PHP script is shorter and easier to understand.

  • identify – describes the format and characteristics of one or more image files
  • convert – convert between image formats as well as resize an image, blur, crop, despeckle, dither, draw on, flip, join, re-sample, and much more

Make sure you have installed ImageMagick package before run this PHP script: yum install ImageMagick

#!/usr/bin/php
<?php
/*
 * usage:
 * resize.php [destination_width] [destination_height]
 * 
 * destination_width and destination_height are optional
 * parameters for destination resize geometry
 * 
 * resize.php will create output directory to save resized
 * images leaving originals intact
 * 
 * This script uses "identify" and "convert" utilities which
 * are members of the ImageMagick suite of tools
 * 
 * yum install ImageMagick
 * 
 */

// input arguments for destination image size
if (count($argv) == 3) {
    $w2 = $argv[1]; // image width
    $h2 = $argv[2]; // image height
}
// set default image width height 800x600
else {
    $w2 = 800; // default image width
    $h2 = 600; // default image height
}

// prepare directory name for saving resized images
// directory name will look like "_800x600"
$dir = "_$w2" . "x$h2";

// create directory (inside current directory) for saving 
// resized images (@ means to be quiet - don't display 
// warning if directory already exists)
@mkdir($dir);

// read files inside current directory
$files = scandir('.');

// open loop for all fetched files in current directory 
foreach ($files as $file){
    // convert file name to lower case
    $file_lowercase = strtolower($file);
    // if file extension is jpg then process image
    if (substr($file_lowercase, -3) == 'jpg'){
        // describe image format and image characteristics
        $identify = shell_exec("identify $file");
        // read image geometry
        preg_match('/(\d+)x(\d+)/', $identify, $matches);
        $g1 = $matches[0]; // image geometry
        $w1 = $matches[1]; // image width
        $h1 = $matches[2]; // image height
        // prepare destination image geometry
        if ($w1 < $h1) $g2 = $h2 . 'x' . $w2;
        else           $g2 = $w2 . 'x' . $h2;
        // to set every image to fixed width (say 320) uncomment this line
        // and call script with big height - resize.php 320 2000
        //$g2 = $w2 .'x' .$h2;
        // print current image status
        print "$file ($g1) -> $dir/$file_lowercase ($g2)\n";
        // resize image and save to destination directory
        system("convert -size $g1 $file -resize $g2 $dir/$file_lowercase");
    }
}
?>

If you want to try script, please download and save PHP code as resize.php. Set permissions to 755 and you can start resize.php like any script from the shell.

Enjoy!

Categories PHP

9 thoughts on “Resize images with PHP script”

  1. I tried using your scripts and got a parsing error on:

    Line 29.
    if ($w1 < $h1) $g2 = $h2 .’x’ .$w2;
    else $g2 = $w2 .’x’ .$h2;

    Could you find the solution to this and post it!

    Thanks in advance.

    SP

  2. I realized that my WordPress site displays curly ‘smart quotes’ – actually like every WordPress site. Smart quotes are nice, but not suitable for program code. So, I disabled smart quotes and after you click on “copy to clipboard” and paste to your local file, PHP script should work now. If your PHP engine has enabled “notice level” then starting script without any parameters (width and height) will print two notices about undefined offset – just ignore them. If you have any further questions, I will gladly help you. Bye!

  3. Nice script, but I was wondering if you could help me with a little modification to it cause i need it to do something a little different.

    I have user submitted pictures that get uploaded to the server each into it’s members id directory. I have a admin area which lists the pictures and output a convert command for me which i then copy and paste into the server command line and recreate a thumbnail and resize for it.

    I was wondering if your script could be modified to basically take in the parameters from the url and create the thumbnail and resize the image if over 450px on either width or height and place the new thumbnail the same directory as the original with a tn_ prefix on the filename.

  4. Abe,
    few years ago, I made a PHP interface to accept and save images to the MySQL database. Uploaded images should fit to the defined box. For example, images greater then 200x200px were decreased while smaller images were just copied. You gave me an idea so I arranged PHP function and prepared two posts:

    Create thumbnail with PHP (1)
    Create thumbnail with PHP (2)

    First post uses ImageMagick utilities identify and convert (like in this post), while second post is pure PHP without external utilities. Hmm, “pure” means to use GD library for image processing and this version is a little bit longer. Both functions produce the same result. Transparency of PNG and GIF images is preserved. Function accepts two parameters. First parameter is absolute path to the image, while second parameter defines box dimension. Thumbnail image is saved to the same directory as original image with the prefix “tn_”. Hope this will help you.

  5. hi friends,

    I love the background of the page where the script is displayed. Kindly give me the hint to the background.

    Peter.

  6. Hi,

    Could you tell me how i can make it so every image has a fixed width of 320 and the height is variable, i cant seem to work it out.

    Hope you can help
    Lucy

  7. @Lucy – I made a small modification in resize.php to support resizing images to fixed width. Here is code (line) that should be uncommented:

    // to set every image to fixed width (say 320) uncomment this line
    // and call script with big height - resize.php 320 2000
    $g2 = $w2 .'x' .$h2;
    

    Actually, previously set value of $g2 will be overwritten with this expression (e.g. 320×2000). Convert utility will resize images to fit to rectangle 320×2000 and the result will be fixed width.

Leave a Comment