Reputation: 235
I have full high quality images and in a specific directly on my website. Using PHP I would like to generate thumbnails from this directory to another directory called 'thumbs'.
I managed to find a code to do a thumbnail of a particular image, but when I tried to do it for a whole folder it didn't work.
Then I found another code from here which seems to be what I'm looking for (only the first part). Unfortunately, I do not know where to insert the source and destination into the code.
/* function: generates thumbnail */
function make_thumb($src,$dest,$desired_width) {
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height*($desired_width/$width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
/* copy source image at a resized size */
imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image,$dest);
}
/* function: returns files from dir */
function get_files($images_dir,$exts = array('jpg')) {
$files = array();
if($handle = opendir($images_dir)) {
while(false !== ($file = readdir($handle))) {
$extension = strtolower(get_file_extension($file));
if($extension && in_array($extension,$exts)) {
$files[] = $file;
}
}
closedir($handle);
}
return $files;
}
/* function: returns a file's extension */
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
Where do I input my source and destination of the folders please?
Upvotes: 1
Views: 2310
Reputation: 22656
The input directory would be $images_dir
in get_files
.
You'll need to loop over the results of this method and call make_thumb
where $dest
will be the final name of that particular file.
Something like this (haven't tested this):
//Set up variables we need
$image_directory = "/some/directory/with/images/";
$thumbs_directory = "/some/directory/for/thumbs/";
$desired_width = 100;
//Get the name of files in $image_directory
foreach(get_files($image_directory) as $image){
//Call make thumb with the given image location and put it into the thumbs directory.
make_thumb($image_directory . $image, $thumbs_directory . $image, $desired_width)
}
Upvotes: 1