Friday, May 27, 2011

11:49 AM

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: identifyand 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
Script was developed on Linux - Fedora Core 9 and tested on Fedora Core 9 and Fedora Core 10.

#!/usr/bin/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
 *
 */

// input arguments for destination image size
$w2 = $argv[1]; // image width
$h2 = $argv[2]; // image height

// both values should be numeric or use default size 800x600
if (!is_numeric($w2) || !is_numeric($h2)){
    $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 alredy 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;
        // 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 save PHP code as resize.php. Set permissions to 755 and you can start resize.php like any script from the shell.
Enjoy!

0 comments: