[PHP5] thumbnail.class.php

Mammouth du PHP | 1885 Messages

08 févr. 2005, 00:37

Classe PHP5 permettant la redimension d'images de types courants soit : JPG, GIF, BMP ou PNG. Les dimensions maximales avant redimension devoit être indiquée si l'on désire que redimension il y ait.
La transparence des PNG est supporté et aucun fond noir ne sera généré. La classe nécessite la compilation de la librairie gd et libexif.

Désolé pour les anglophobes, je code toujours en anglais. :)
<?php

class thumbnail {

	private $types = array(
		IMAGETYPE_JPEG => 'jpeg',
		IMAGETYPE_GIF => 'gif',
		IMAGETYPE_PNG => 'png'
	);

	private $thumbnaildir = './';

	public $maxWidth = 0;
	public $maxHeight = 0;


	public function __construct($thumbnaildir=NULL) {

		if (FALSE === extension_loaded('gd')) {
			throw new exception('gd must be compiled to use this class.');
		}

		if (FALSE === extension_loaded('exif')) {
			throw new exception('libexif must be compiled to use this class.');
		}

		$this->thumbnaildir = $thumbnaildir;

	}

	public function execute($filename) {

		if (FALSE === file_exists($filename)) {
			throw new exception('No such file.');
		}

		if (FALSE === $type = exif_imagetype($filename)) {
			throw new exception('File is not an image.');
		}


		if (FALSE === array_key_exists($type, $this->types)) {
			throw new exception('Image type is not supported by this class.');
		} else {
			$type = $this->types[$type];
		}

		try {
			$this->validation();
			$result = $this->resize($filename, $type);
		} catch ( exception $e ) {
			throw $e;
		}

		return $result;
	}

	private function resize($filename, $type) {

		if (0 === $this->maxHeight && 0 === $this->maxWidth) {
			return TRUE;
		}

		list($width, $height) = getimagesize($filename);

		if ($width <= $this->maxWidth && $height <= $this->maxHeight) {
			return TRUE;
		}

		if ($width > $height) {
			$thumbnail_width = $this->maxWidth;
			$thumbnail_height = (int) ($this->maxWidth * $height / $width);
		} else {
			$thumbnail_width = (int) ($this->maxHeight * $width / $height);
			$thumbnail_height = $this->maxHeight;
		}

		$read = 'imagecreatefrom' . $type;
		$write = 'image' . $type;

		if (FALSE === function_exists($write) ) {
			throw new exception('Image type is not supported by your GD library.');
		}

		if (FALSE === $img = $read($filename) ) {
			throw new exception('An exception occured while opening original file.');
		}

		if ('gif' === $type) {
			$des = imagecreate($thumbnail_width, $thumbnail_height);
			$resize = 'imagecopyresized';
		} else {
			$des = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
			$resize = 'imagecopyresampled';
		}

		if ('png' === $type) {

			if (FALSE === imagealphablending($des, FALSE) ) {
				throw new exception('Enable to activate full alpha information.');
			}
			if (FALSE === imagesavealpha($des, TRUE)) {
				throw new exception('Enable to activate full alpha information.');
			}
		}

		if (FALSE === $resize($des, $img, 0, 0, 0, 0, $thumbnail_width, $thumbnail_height, $width, $height)) {
			throw new exception('An exception occured while resizing the original file.');
		}

		if (FALSE === $write($des, $this->thumbnaildir . '/' . $filename)) {
			throw new exception('An exception occured while writing thumbnail file.');
		}

		return TRUE;
	}


	private function validation() {

		if (FALSE === is_writable($this->thumbnaildir)) {
			throw new exception('Thumbnails directory is not writable.');
		}

		if (FALSE === is_int($this->maxWidth) || FALSE === is_int($this->maxHeight)) {
			throw new exception('Maximum dimensions must be integer.');
		}

		if (0 > $this->maxWidth || 0 > $this->maxHeight) {
			throw new exception('Maximum dimensions must be positive integer.');
		}
	}


}

// Exemple d'utilisation
try {
	$thumb = new thumbnail('./thumbs/');
	$thumb->maxWidth = 80;
	$thumb->maxHeight = 60;
	$thumb->execute('image.png');
} catch (exception $e) {

	echo '<br />';
	echo 'Error message: ' , $e->getMessage() , '<br />';
	echo 'Error code: ' , $e->getCode() , '<br />';
	echo 'Script Name: ' , $e->getFile() , '<br />';
	echo 'Line Number: ' , $e->getLine() , '<br />'; 
}
?>
Modifié en dernier par Xenon_54 le 31 mai 2005, 03:57, modifié 1 fois.

Eléphanteau du PHP | 24 Messages

08 févr. 2005, 01:03

joli, c'est trés utile. mais dis, la qualitée de l'image n'est pas réduite? j'avais fait un truc du genre (sans passser par les class) et l'image obtenue était médicore. bon, c'était en php4. alors, si ça change klk chose, je ne sais pas

Mammouth du PHP | 1885 Messages

08 févr. 2005, 01:07

Il te faut utiliser les fonctions imagecreatetruecolor() et imagecopyresampled() si tu désires redimensionner des images de type JPG ou PNG, afin de conserver la netteté.
Cependant, on part toujours avec l'idée du fait que l'on réduit une image et donc sa qualité. Ne pas oublier.

;)

Petit nouveau ! | 1 Messages

28 mai 2005, 18:11

Salut,
La doc PHP dit que imagecreatefromwbmp c'est pour gérer des images de type Wireless BMP et pas Windows BMP. Ainsi avec un BMP classique le script ne marche pas ? As-tu testé ? Y a t'il un moyen de charger une image BMP en php ?
Merci
A+

Mammouth du PHP | 1885 Messages

31 mai 2005, 03:56

:-k

En effet, tu as parfaitement raison. Après avoir parcouru la documentation, il semblerait que le format BMP ne soit pas du tout supporté. Je retire donc ce format de la classe.

Merci de l'attention apportée.

:)
La programmation est l'expression de la poésie d'un programmeur
Génération PHP

Mammouth du PHP | 19672 Messages

31 mai 2005, 08:42

Si je peux me permettre:
retirer le format BMP est peut-être une erreur: par contre transformer pour créer du WBMP pour ceux qui font du WAP, ça pourrait être utile :)
Codez en pensant que celui qui maintiendra votre code est un psychopathe qui connait votre adresse :axe: