TheRogerLAB Codes

Create a thumbnail in PHP

  July, 2021

Introduction

Thumbnails are reduced-size versions of pictures or videos. They are ideally implemented on web pages as separate, smaller copies of the original image, in part because one purpose of a thumbnail image on a web page is to reduce bandwidth and download time.

Step 1: Define a function to process the file in php

<?php
function processFile($originalFile){
  //$originalFile is the path of the picture ('images/file.jpg')
  $image = imagecreatefrompng($originalFile);

  //the new name and destiny path
  $filename = 'thumbnail/image.jpg';

  $thumb_width = 280;
  $thumb_height = 187;

  $width = imagesx($image);
  $height = imagesy($image);

  $original_aspect = $width / $height;
  $thumb_aspect = $thumb_width / $thumb_height;

  if ( $original_aspect >= $thumb_aspect ) {
    // If image is wider than thumbnail (in aspect ratio sense)
    $new_height = $thumb_height;
    $new_width = $width / ($height / $thumb_height);
  } else {
    // If the thumbnail is wider than the image
    $new_width = $thumb_width;
    $new_height = $height / ($width / $thumb_width);
  }

  $thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

  // Resize and crop
  imagecopyresampled($thumb,
    $image,
    0 - ($new_width - $thumb_width) / 2// Center the image horizontally
    0 - ($new_height - $thumb_height) / 2// Center the image vertically
    00,
    $new_width, $new_height,
    $width, $height);

  imagejpeg($thumb, $filename, 80);
}
?> 
RATE THIS ARTICLE
4.8
13
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com