The Web Blinders logo

Programming

PHP - How to generate thumbnails for images (png, jpg, gif, webp) with out Imagick

Thumbnails of images save bandwidth* and also increase user experience*. You could use Imagick but in some cases it may not be installed in your server.Here you will see how to generate thumbnails easily with out imagick.
PHP - How to generate thumbnails for images (png, jpg, gif, webp) with out Imagick
Snapshot of function which generates thumbnails

We will use SimpleImage

Go to https://github.com/claviska/SimpleImage, download and extract SimpleImage.php.

generateThumbnail() returns true if a thumbnail is created and it will create thumbnails for PNG, JPG, GIF, WEBP formats

You can specify WIDTH and HEIGHT of your thumbnail image.By default it is 300. View code for more.


use claviska\SimpleImage;
include 'path/to/SimpleImage.php';

class ThumbNailer extends SimpleImage{
    /**
     * Generates thumbnail for PNG,JPG,GIF,WEBP FORMATS
     * Returns true if thumbnail is created
     *
     * @param string $source - path to the source file  
     * @param string $destination - destination path along with file name
     * @param integer $width - width of the thumbnail image
     * @param integer $height - height of the thumbnail image
     * @return bool
     */
    public function generateThumbnail($source,$destination,$width=300,$height=300){
        try{
            $this->fromFile($source)
            ->thumbnail($width, $height, "center")
            ->toFile($destination); 
            return true; 
        }
        catch(Exception $e){
            return false;
        }
    }
}

$tn=new ThumbNailer();
// Usage example
echo $tn->generateThumbnail('path/to/source/A-PNG-IMAGE.png','path/to/destination/thumbnail-images/png.png'); 
echo $tn->generateThumbnail('path/to/source/A-JPG-IMAGE.jpg','path/to/destination/jpg.jpg');                 
echo $tn->generateThumbnail('path/to/source/A-GIF-IMAGE.gif','path/to/destination/gif.gif');                            
   
  • To see it in action , go to https://github.com/thewebblinders/php-thumbnails-for-images, download and extract files.
  • if you look at thumbnail-images folder, it will be empty
  • Now run index.php on your server,you will see thumbnails being created in the folder thumbnail-images for the images located in source-images

Need developers ?

if so, send a message.

thewebblinders@gmail.com

More Programming from our blog

SEARCH FOR ARTICLES