A PHP script to resize all images in a directory

This is a crude hack to resize images in a directory. The script is invoked as:

shrink <new_x> <new_y> <file> <file> <file> ...

You’ll need PHP with the GD library. That’s php5-gd on FreeBSD.


#!/usr/local/bin/php
# The output is JPEG, quality 88.

<?php



// Fuction to resize images, originally by D. Weimer.
// Code reformatting done, and '>' changed to '<'.
// http://www.dweimer.net/?page=help&subpage=imageresize
function resize($img,$nx,$ny)
{
    // $x and $y: original image's sizes.
    $x = imagesx($img);
    $y = imagesy($img);

    // Here, $nx and $ny are the minimal desired dimensions.
    if ( ($x/$nx) < ($y/$ny) )
    {
        $ny = round( $y * ($nx/$x) );
    }
    else
    {
        $nx = round( $x * ($ny/$y) );
    }

    $nimg = imagecreatetruecolor($nx,$ny);
    imagecopyresampled($nimg,$img,0,0,0,0,$nx,$ny,$x,$y);
    imagedestroy($img);
    return($nimg);
}



$arguments = $_SERVER['argv'];          // What the user wants to process.
array_shift($arguments);                // 1st element is the path to the script itself.
$newx = array_shift($arguments);        // 2nd is the new desired x dimension.
$newy = array_shift($arguments);        // 3rd is new y.
                                        // all the remaining args are images.

foreach ( $arguments as $arg )          // Go over user's shown items (single or "heaps").
{
    foreach (glob("$arg") as $filename) // Go over every file in a "heap".
    {
        $image = file_get_contents($filename);
        $image = imagecreatefromstring($image);

        $image = resize($image, $newx, $newy);

        imagejpeg( $image, $filename, 88 ); // WARNING!!! Writes JPEG by default!
    }
}


?>

I was too lazy to go searching for something pre-made.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: