Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GD image batch processing from directory

Tags:

php

gd

Really racking my brain, I've been looking into this for 2+ days.

Goal? Click/select a subdirectory with images; on Submit, a batch process will run using GD on the whole DIR chosen, creating thumbs in a /thumbs folder on the same server.

Status? I can do this for a single file at a time, need to do multiple files at once.

Here's my functioning one-off code:

$filename = "images/r13.jpg";

list($width,$height) = getimagesize($filename);

$width_ratio = 166 / $width;
if ($height * $width_ratio <= 103)
{
    $adjusted_width = 166;
    $adjusted_height = $height * $width_ratio;
}
else
{
    $height_ratio = 103 / $height;
    $adjusted_width = $width * $height_ratio;
    $adjusted_height = 103;
}

$image_p = imagecreatetruecolor(166,103);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p,$image,ceil((166 - $adjusted_width) / 2),ceil((103 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height);

imagejpeg($image_p,"images/thumbs/r13.jpg",70);

As you can see, the script is targetting a single file, I would like to iterate through a directory instead of specifying a name.

(I will also look into imagemagick, but at the moment it is not an option.)

I'll keep going through SO etc, but any help would be tremendous.

Thanks.

like image 852
JWC_WDC Avatar asked Jun 22 '26 01:06

JWC_WDC


1 Answers

you need to make a function from this code:

function processImage($filename){
    list($width,$height) = getimagesize($filename);

    $width_ratio = 166 / $width;
    if ($height * $width_ratio <= 103)
    {
        $adjusted_width = 166;
        $adjusted_height = $height * $width_ratio;
    }
    else
    {
        $height_ratio = 103 / $height;
        $adjusted_width = $width * $height_ratio;
        $adjusted_height = 103;
    }

    $image_p = imagecreatetruecolor(166,103);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p,$image,ceil((166 - $adjusted_width) / 2),ceil((103 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height);

    imagejpeg($image_p,"images/thumbs/".basename($filename),70);
    imagedestroy($image_p);
}

Please note last two lines of this function: it writes thumb basing on passed fiulename and destroys resource, to free memory.

Now apply this to all files in directory:

foreach(glob('images/*.jpg') AS $filename){
    processImage($filename);
}

and basically that's it.

like image 101
dev-null-dweller Avatar answered Jun 23 '26 21:06

dev-null-dweller