Créer des aperçus d’image très facilement avec GD
Très utile pour créer une vignette d’une image, voici un script que j’utilise déjà un pti moment : thumb.php
Ce script php permet :
- Un resize de qualité
- Prise en charge de tous les formats d’image reconnus par GD
- Mise en cache des images générées
- L’image n’est pas resizée si plus petite que les dimensions fixées
- Une manière sûre de ne pas dépasser une dimension fixée
Voici comment utiliser le script :
<img src="thumb.php?i=chemin_image&w=150&h=150">
i => Chemin de l’image sur le serveur
w => Largeur maximale
h => Hauteur maximale
Pour éviter de déformer l’image, je vous conseille d’utiliser dans tous les cas une hauteur égale à la largeur.
Le script :
<?php
#@
#@ Load a picture and take few parameters
#@ Build cache file for thumbnail view
#@
#@ Created by Guillaume DE LA RUE <http://web2ajax.fr/>
#@
#@
#@ Local Function to get extension
#@ ————————————————————
function _getExtension($file_name) {
$file_infos = pathinfo($file_name);
return ‘.’.$file_infos['extension'] ;
}
#@
#@ Config
#@ ————————————————————
$cache_dir = ‘common_files/cache/’ ;
#@
#@ Get url params
#@ ————————————————————
$width = $_GET['w'] ;
$height = $_GET['h'] ;
$image_file = $_GET['i'] ;
$cache_force = $_GET['nocache'] ;
#@
#@ Set vars
#@ ————————————————————
$image_file_extension = _getExtension($image_file, true) ;
$image_file_basename = @basename($image_file, $image_file_extension) ; // Filename without extension ‘.jpg’
$thumb_file = $image_file."_".$width."_".$height ;
#@
#@ Infos in image_file
#@ ————————————————————
## Get md5 of files location
//$image_file_md5 = md5($image_file) ;
$thumb_file_md5 = @md5($thumb_file) ;
#@
#@ If thumbnail doesn’t exists create it !
#@ ————————————————————
if ( ! @file_exists($cache_dir.$thumb_file_md5.$image_file_extension) || $cache_force == "true") {
## Get infos on file with exif
$image_infos = @getimagesize($image_file) ;
$width_original = $image_infos[0] ;
$height_original = $image_infos[1] ;
## Detect Portait( => 0) / paysage ( => 1)
if ( $width_original <= $height_original ) {
$image_type = 0 ;
} else {
$image_type = 1 ;
}
## Define best size to thumb depending params
if ( $image_type == 0 ) {
$best_height = $height ;
$best_width = (int) ( $width_original * ($height / $height_original ) ) ;
} else {
$best_width = $width ;
$best_height = (int) ( $height_original * ( $width / $width_original ) ) ;
}
## If picture is little than wanted => don’t stretch it, juste create a standard thumbnail
if ( $width_original < $width && $height_original < $height ) {
$best_width = $width_original ;
$best_height = $height_original ;
}