php resize image recursive

Wednesday 10th, Oct, 2018 | #PHP #Photographer


I write this script one day that I had the need to resize a huge amount of images that were inside several folders and I needed to maintain the original directory structure. As a solution I made a PHP command line script that allows you to do it very quickly and effectively. It also applies a sharpen filter to the edges of the image so that it looks better in thumbnails

PHP Script with imagecopyresampled GD


#!/usr/bin/php

#JopsConvertedPHP.php
#USAGE: Command LINE
# php JopsConvertedPHP.php folder_origen folder_target size_pixel filter_for_exclude
#Example
# php JopsConvertedPHP.php c:\pics c:\lowpics 500 jpg


$dirO=$argv[1];
$dirD=$argv[2];
$myMaxSide=$argv[3];
$filtro=$argv[4];

echo $filtro;



copy_recursively($dirO,$dirD,$filtro);

function copy_recursively($from_dir, $to_dir, $regex) 
{	echo "\n\nDir:".$from_dir. "\n\n";
	$dh = opendir($from_dir);
	
	while ($entry = readdir($dh))
	{	
		if ($entry!= "." && $entry != ".."):
  		
			$source = "$from_dir/$entry";
			$destination = "$to_dir/$entry";
			
			if(is_dir($source)){
				echo "\n\nDir:".$source. "\n\n";
				if(!file_exists($destination)) {mkdir($destination, 0700, true) or die('Fallo al crear carpetas...');}
				
				copy_recursively($source, $destination, $regex);
			}else{
				if(preg_match("/.jpg|$filtro/",$entry)):
					print "Origen: $source\n";
					print "Destino: $destination\n";
					//
					try{
						global $myMaxSide;
						$imgOut = resampledGD($source,$myMaxSide);
						imagejpeg($imgOut, $destination, 70);
						imagedestroy($imgOut);
						
					}

					catch(Exception $e){
						print "Error en: $source\n";	
					}
				
				endif;
				
			}
		
		endif;
	}
	
	
	
	
}

function resampledGD($imgUrl,$maxSide) {
	
$imagen_thumb = imagecreatefromjpeg($imgUrl);
$imgAncho = imagesx($imagen_thumb);
$imgAlto =imagesy($imagen_thumb);


if($imgAncho>$imgAlto)
{
	$ancho = $maxSide; 
	$alto =  round($imgAlto*$ancho/$imgAncho);
	
}
else
{
	$alto = $maxSide; 
	$ancho = round($imgAncho*$alto/$imgAlto);
}

$calidad = 80 ;	



$img = imagecreatetruecolor($ancho,$alto);
imagecopyresampled($img,$imagen_thumb,0,0,0,0, $ancho,$alto,$imgAncho,$imgAlto);
imagefilter($img,  IMG_FILTER_SMOOTH, -24);  
#With -24 you can add sharpen
		
return $img;	
	
}

Image sharpening diference

no sharpen No Sharpen
no sharpenSharpen