You could use something like this below. First you verify if the filename has the width and hieght in its name and then check if a file exists without those values. If not you can delete the file. You could also write some regular expression for this job.
But you need to be aware that you cannot accept uploads of a file that already uses that same filenaming format. For example if you upload a file called "some-background-image_1920x1020.jpg" then the generated thumbnail would be "some-background-image_1920x1020_100x50.jpg" (or perhaps "some-background-image_1920x1020_100x53.jpg" if you preserve the aspect ratio). If you loop trough all your files in the directory then "some-background-image_1920x1020.jpg" would be removed because the file "some-background-image.jpg" does not exists.
You need to extend it somewhat to check this, or rename such a file during upload or place your thumbnails in a separate folder.
PHP Code:
$file = 'example_100x50.jpg';
$position_dot = strrpos($file, '.');
$position_underscore = strrpos($file, '_');
if ($position_dot && $position_underscore && $position_dot > $position_underscore) {
$sizeString = substr($file, $position_underscore + 1, ($position_dot - $position_underscore) -1 );
// $sizeString should contain something like 100x50
$sizesArray = explode('x', $sizeString);
if (count($sizesArray) == 2 && is_numeric($sizesArray[0]) && is_numeric($sizesArray[1])) {
// The filename is a generated thumbnail
// Remove the sizes string and underscore from the filename
$originalFile = str_replace('_' . $sizeString, '', $file);
if (!is_file(FCPATH . 'images/' . $originalFile)) {
// Remove this thumbnail because the original file does not exists anymore.
if (@unlink(FCPATH . 'images/' . $file)) {
// File was removed
} else {
// Some error handeling, unlink was unsuccessfull
}
}
}
}