Search code examples
phpimage-processingscaleimage-resizing

How to scale down an image on the server side with PHP?


I have some images that are pulled from a server and $imgUrl holds the path of the image.

Right now I use <img src="<?php echo $imgUrl ?>" width="100" height="200"/> or CSS to scale down the image, but I want to do it in PHP so that I will serve already scaled images to the DOM

Any ideas?

Thanks


Solution

  • This solution will cause the thumb to be created when it is requested for the first time. All future requests will fetch the already created thumb. It is using ImageMagick:

    HTML:

    <img src="script.php?img=example" />
    

    PHP (script.php):

    $width  = 140;
    $height = 80;
    $image  = $_GET['img'];
    $ext    = 'png';
    
    // Check if file exists
    if ( ! file_exists('/path/to/the/'.$image.'.'.$ext))
    {
        die('Unable to process the requested file.');
    }
    
    // Check if a thumb already exists, otherwise create a thumb
    if (file_exists('/path/to/the/'.$image.'_thumb.'.$ext))
    {
        $img = new imagick('/path/to/the/'.$image.'_thumb.'.$ext);
    }
    else
    {
        $img = new imagick('/path/to/the/'.$image.'.'.$ext);
        $img->setImageFormat($ext);
        $img->scaleImage($width, 0);
        $img->cropImage($width, $height, 0, 0);
        $img->writeImage('/path/to/the/'.$image.'_thumb.'.$ext);
    }
    
    // Return as an image
    header('Content-Type: image/'.$ext);
    echo $img;