• Home
  • PHP
  • Resize all images from a folder to several separate folders (PHP)

Resize all images from a folder to several separate folders (PHP)

Below is the piece of PHP code that will take all JPG images in your website’s folder, will resize each of them into two different sizes (260×195 and 152×114 in our example) and will place resized files into separate folders.

ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
set_time_limit(60);
$lookInFolder = $_SERVER['DOCUMENT_ROOT'].'/eng/images/items/';
$saveInFolder1 = $_SERVER['DOCUMENT_ROOT'].'/eng/images/items/152x114/';
$saveInFolder2 = $_SERVER['DOCUMENT_ROOT'].'/eng/images/items/260x195/';
echo 'LOOK FOR: '.$lookInFolder.'<br>';
echo 'SAVE IN 1: '.$saveInFolder1.'<br>';
echo 'SAVE IN 2: '.$saveInFolder2.'<br>';
$files = scandir($lookInFolder);
$count = 1;
foreach($files as $file) {
    $filename = strtolower($file);
    if(substr($filename, -3) == 'jpg' && substr($filename, -12) != '_resized.jpg'){
        echo $count.' ---> '.strtolower($file).'<br>';
        $count++;
        $filePath = $lookInFolder.$file;
        //do resize
        //260x195 and 152x114
        list($sw, $sh) = getimagesize($filePath);
        $ar=$sw/$sh;
        [email protected]($filePath);
        [email protected](260,195);
        [email protected](152,114);
        if((@imagecopyresampled($dest260,$srci,(($ar<(4/3))?(260-195*$ar)/2:0),(($ar>(4/3))?(195-260/$ar)/2:0),0,0,(($ar<(4/3))?195*$ar:260),(($ar>(4/3))?260/$ar:195),$sw,$sh))&&(@imagecopyresampled($dest152,$srci,(($ar<(4/3))?(152-114*$ar)/2:0),(($ar>(4/3))?(114-152/$ar)/2:0),0,0,(($ar<(4/3))?114*$ar:152),(($ar>(4/3))?152/$ar:114),$sw,$sh))) {
            $path260=str_replace('images/items','images/items/260x195',$filePath);
            $path152=str_replace('images/items','images/items/152x114',$filePath);
            if(!imagejpeg($dest260,$path260,75))
                echo 'nope';
            if(!imagejpeg($dest152,$path152,75))
                echo 'nope';
        } else {
            echo 'not created';
        }
    }
}
?>

Tags: , ,

Yandex.Metrica