Search code examples
phpbatch-processing

How to Batch resize images with PHP


I am maintaining an old website. Now my client wants to add more than 6000 products. The product images have different sizes. I have to apply batch process. I have to resize them all to a thumb size of 230x230. Is there any way to do if from PHP? If so how?

I have to read all content from different folders which are inside a main images folders. This images folder has 40 subfolders. Each folder name is the category name and the images inside it are products (image).

if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
    // copy file
    if(imagejpeg($NewCanves,$DestImage,$Quality))
    {
        imagedestroy($NewCanves);
        return true;
    }
}

Solution

  • With php you can read the files inside a folder using

    $images= glob("*"); // * will address all files
    // or
    $images= glob("*.jpg"); // this will address only jpg images
    

    Then loop through $images

    foreach ($images as $filename) {
       //resize the image
       if(resizeImage($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality)){
         echo $filename.' resize Success!<br />';
       }
    }
    
    function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
    {
        list($iWidth,$iHeight,$type)    = getimagesize($SrcImage);
    
        //if you dont want to rescale image
    
        $NewWidth=$MaxWidth;
        $NewHeight=$MaxHeight;
        $NewCanves              = imagecreatetruecolor($NewWidth, $NewHeight);
    
        // Resize Image
        if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
         {
            // copy file
            if(imagejpeg($NewCanves,$DestImage,$Quality))
            {
                imagedestroy($NewCanves);
                return true;
            }
        }
    }