Filter images based on Image size using PHP and localhost

Posted by: Alex on December 10, 2014

As well as PHP being a very easy code to use language on the web, PHP and localhost can be a great setup to do some basic file manipulation and sorting on your computer.

In this following codebyte the basic principle is we have a folder of images of varying sizes/dimensions, and we want to filter out all of the low-resolution images.

The PHP code loops over a folder of our choosing ($current_folder), using a foreach loop on each image/file, checking if either the $width or $height is under 400(px), if it is, then it moves it to the trash folder ($trash_folder) so that we then have one folder of images of low resolution.

<?php
// Change folder_name_here to the the folder containing your files/images you want to loop over. [Leave the trailing / alone]
$current_folder = "folder_name_here"."/";
// A folder to move the files that don't meet our rules. [Leave the trailing / alone]
$trash_folder = "trash"."/";
$files = scandir($current_folder);
foreach ($files as $file) {
  $image_info = list($width, $height) = getimagesize($current_folder.$file);
  if ($width < 400 || $height < 400) {
    rename($current_folder.$file, $trash_folder.$file);
  }
}
?>