PHP class to create image thumbanils

Some years ago, I wrote a PHP class to create image thumbnails because I needed it for a project. There were needed certain things that I could not able to find in other PHP classes, and I decided to create one with my specific needs. Today, after some improvements and fixes to perfect it, I have decided to share it with anyone that wants to use it.

Features of this class:

  • It is possible to work with the main image formats (jpg, png, and gif).
  • It is possible to resize images setting a width or a height and maintaining the original proportion.
  • It is possible to crop the images to a custom size maintaining its original proportion (it is also possible to chose the cropping position).
  • It is possible to store the resulting image in the server.
  • Is is possible to show the image in the browser on the fly.
  • It is possible to keep the alpha channel of PNG and GIFs images.

This class needs the GD library installed in the server (included in PHP from version 4.3)

PHP class to create image thumbnails

class Thumb {

	private $image;
	private $type;
	private $mime;
	private $width;
	private $height;

	//---Method to read the image
	public function loadImage($name) {

		//---Storing the image dimensions
		$info = getimagesize($name);

		$this->width = $info[0];
		$this->height = $info[1];
		$this->type = $info[2];
		$this->mime = $info['mime'];

		//---Create a new image depending on the original format
		switch($this->type){

			case IMAGETYPE_JPEG:

				$this->image = imagecreatefromjpeg($name);

			break;

			case IMAGETYPE_GIF:

				$this->image = imagecreatefromgif($name);

			break;

			case IMAGETYPE_PNG:

				$this->image = imagecreatefrompng($name);

			break;

			default:

				trigger_error('It is not possible to create a thumbnail using the specified format', E_USER_ERROR);

		}

	}

	//---Method to store the image
	public function save($name, $quality = 100, $type = false) {

		//---If the format is not present, chose the format of the original image
		$type = ($type) ? $type : $this->type;

		//---Store the image using the correct format
		switch($type){

			case IMAGETYPE_JPEG:

				imagejpeg($this->image, $name . image_type_to_extension($type), $quality);

			break;

			case IMAGETYPE_GIF:

				imagegif($this->image, $name . image_type_to_extension($type));

			break;

			case IMAGETYPE_PNG:

				$pngquality = floor($quality / 100 * 9);

				imagepng($this->image, $name . image_type_to_extension($type), $pngquality);

			break;

			default:

				trigger_error('The specified image format is not correct', E_USER_ERROR);

		}

	}

	//---Method to show an image on the fly
	public function show($type = false, $base64 = false) {

		//---If the format is not present, chose the format of the original image
		$type = ($type) ? $type : $this->type;

		if($base64) ob_start();

		//---Show the image using the correct format
		switch($type){

			case IMAGETYPE_JPEG:

				imagejpeg($this->image);

			break;

			case IMAGETYPE_GIF:

				imagegif($this->image);

			break;

			case IMAGETYPE_PNG:

				$this->prepareImage($this->image);

				imagepng($this->image);

			break;

			default:

				trigger_error('The specified image format is not correct', E_USER_ERROR);

				exit;

		}

		if($base64) {

			$data = ob_get_contents();

			ob_end_clean ();

			return 'data:' . $this->mime . ';base64,' . base64_encode($data);

		}

	}

	//---Method to resize the image maintaining its proportion
	public function resize($value, $prop){

		//---Determine the resize property
		$prop_value = ($prop == 'width') ? $this->width : $this->height;
		$prop_versus = ($prop == 'width') ? $this->height : $this->width;

		//---Determine the opposite resize property
		$pcent = $value / $prop_value;
		$value_versus = $prop_versus * $pcent;

		//---Create the image using the resize property
		$image = ($prop == 'width') ? imagecreatetruecolor($value, $value_versus) : imagecreatetruecolor($value_versus, $value);	

		//---Treat the image
		if($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG) $this->prepareImage($image);	

		//---Make a copy of the image taking into account the resize property
		switch($prop){

			case 'width':

				imagecopyresampled($image, $this->image, 0, 0, 0, 0, $value, $value_versus, $this->width, $this->height);

			break;

			default:

				imagecopyresampled($image, $this->image, 0, 0, 0, 0, $value_versus, $value, $this->width, $this->height);

		}

		//---Update the image and its dimensions
		$this->width = imagesx($image);
		$this->height = imagesy($image);
		$this->image = $image;

	}

	//---Method to extract a portion of the image maintaining its proportion
	public function crop($cwidth, $cheight, $pos = 'center') {

		$pcent = min($this->width / $cwidth, $this->height / $cheight);
		$bigw = (int) ($pcent * $cwidth);
		$bigh = (int) ($pcent * $cheight);

		//---Create the image
		$image = imagecreatetruecolor($cwidth, $cheight);

		//---Treat the image
		if($this->type == IMAGETYPE_GIF || $this->type == IMAGETYPE_PNG) $this->prepareImage($image);

		//---Depending of the crop position
		switch($pos){

			case 'left':

				imagecopyresampled($image, $this->image, 0, 0, 0, abs(($this->height - $bigh) / 2), $cwidth, $cheight, $bigw, $bigh);

			break;

			case 'right':

				imagecopyresampled($image, $this->image, 0, 0, $this->width - $bigw, abs(($this->height - $bigh) / 2), $cwidth, $cheight, $bigw, $bigh);

			break;

			case 'top':

				imagecopyresampled($image, $this->image, 0, 0, abs(($this->width - $bigw) / 2), 0, $cwidth, $cheight, $bigw, $bigh);

			break;

			case 'bottom':

				imagecopyresampled($image, $this->image, 0, 0, abs(($this->width - $bigw) / 2), $this->height - $bigh, $cwidth, $cheight, $bigw, $bigh);

			break;

			default:

				imagecopyresampled($image, $this->image, 0, 0, abs(($bigw - $this->width) / 2), abs(($bigh - $this->height) / 2), $cwidth, $cheight, $bigw, $bigh);

		}

		$this->width = $cwidth;
		$this->height = $cheight;
		$this->image = $image;

	}

	//---Private method to treat the images before show them
	private function prepareImage($image){

		//---Depending on the image type
		switch($this->type){

			case IMAGETYPE_GIF:

				$background = imagecolorallocate($image, 0, 0, 0);
				imagecolortransparent($image, $background);

			break;

			case IMAGETYPE_PNG:

				imagealphablending($image, FALSE);
				imagesavealpha($image, TRUE);

			break;

		}

	}

}

Public methods

//Reads the image from the specified path
loadImage(string $name)
$name Image path
//Stores the image in the specified path
save(string $name [, int $quality = 100] [, int $type = false])
$name Image path
$quality Image quality with a value between 0 and 100
$type Image type defined by a constant IMAGETYPE_XXX (IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF). It is optional, if it is not sent, the original format will be used
// Shows the image directly on the page or returns a base64 representation of it
show([int $type = false] [,boolean $base64 = false])
$type Image type defined by a constant IMAGETYPE_XXX (IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF). It is optional, if it is not sent, the original format will be used
$base64 Specifies if the image flow should be printed on the page or should be returned as a base64.
//Resizes the image maintaining its proprtion
resize(int $value, string $reference)
$value The value of width or height that should be used to resize the image
$reference String that defines if the image should be resized taking into account the with or the height (possible values: ‘width’ or ‘height’)
//Crops the image creating a thumbnail of it
crop(int $width, int $height [, string $position = 'center'])
$width Width of the thumbnail
$height Height of the thumbnail
$position The position from which the thumbnail should be extracted (possible values: ‘top’, ‘right’, ‘bottom’, ‘left’ or ‘center’)

Functional demo

Open demo

Download the files

Download the files of the PHP class to create image thumbnails.

(3 votes, average: 3.67 Out Of 5)
Share this post:

4 Comments

  1. Very nice. You could have added parameter info to each function using Netbeans, such as: /**
    * Stores the image in the specified path
    * @param type $name Image path
    * @param type $quality Image quality with a value between 0 and 100
    * @param type $type Image type defined by a constant IMAGETYPE_XXX (IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF). It is optional, if it is not sent, the original format will be used
    */
    public function save($name, $quality = 100, $type = false){

    }

    • Hi Andres,

      Thanks for your comment. There was an error with my email provider and I was not receiving notifications about new comments.

      Regards

It is possible to insert code fragments between <pre></pre> tags and HTML or XML code between <xmp></xmp> tags.

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.