Create thumbnails with php

Published on Jun 1 2018

An example of how to create a thumbnail image from source image using PHP GD and Image Functions. (PHP 4, PHP 5, PHP 7)

<?php
/**
* makeThumb()
* @parm $src - site/path/to/file
* @parm $dest - site/path/to/file/thumb/
* handle ['jpg','jpeg','png','gif']
* overwrite = true;
*/
// site path
$site_path = '/var/www/clients/client6/web8/web';
// images dir
$fp = $site_path.'/assets/uploads/image/products';
// thumb dir
$fp_thumb = $site_path.'/assets/uploads/image/products/thumb/';
// thumb width
$width = 100;
// array of files
$images = false;
// filter dot, other
$_exclude = ['.','..'];
// scan the source dir
if (is_readable($fp)){$images = array_diff(scandir($fp), $_exclude);}
// iterate over result and makeThumb()
if($images)
{
    foreach($images as $image)
    {
        $src = $fp.'/'.$image;
        makeThumb($src,$fp_thumb,$width);
    }
}
// ------------------------------------------
function makeThumb($src, $dest, $thumb_width) 
{
    // files only
    if(!is_file($src)){return;}
    // array[]
    $path_parts = pathinfo($src);   
    if(!$path_parts['extension']){return;}
    $ext = strtolower($path_parts['extension']);
    // write thumb with this name.ext
    $fname = $path_parts['filename'].'.'.$ext; 
    // init
    $source_image = false;
    switch(true)
    {
        case $ext === 'jpg' || $ext === 'jpeg':
            $source_image = imagecreatefromjpeg($src);
            break;
        case $ext === 'png':
            $source_image = imagecreatefrompng($src);
            break;
        case $ext === 'gif':
            $source_image = imagecreatefromgif($src);
            break;
    }   
    // creates the thumbnail
    if($source_image)
    {
        $width = imagesx($source_image);
        $height = imagesy($source_image);
        /* set height of thumbnail relative to width */
        $thumb_height = floor($height * ($thumb_width / $width));
        /* create a tmp image */
        $tmp_img = imagecreatetruecolor($thumb_width, $thumb_height);
        /* copy source image at a resized size */
        if(imagecopyresampled($tmp_img, $source_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height))
        {
            // write thumbnail
            switch(true)
            {
                case $ext === 'jpg' || $ext === 'jpeg':
                    imagejpeg( $tmp_img, "{$dest}{$fname}" );
                    break;
                case $ext === 'png':
                    imagepng( $tmp_img, "{$dest}{$fname}" );
                    break;
                case $ext === 'gif':
                    imagegif( $tmp_img, "{$dest}{$fname}" );
                    break;
            }
        }
        unset($tmp_img);
        echo $dest.$fname.'<br>';
    }
}
?>

Tested and working on debain.home LAMP stack 2018.

resource:


Updated by db Jun 1 2018 , filed under PHP