Op het internet zijn tal van scripts te vinden om miniaturen te maken. Na een speurtocht uiteindelijk gekozen zelf een functie hiervoor te schrijven met de volgende functionaliteiten cq vereisten:
- Zowel de hoogte als de breedte in kunnen stellen
- De miniatuur dient altijd gevuld te zijn, wanneer de verhouding dus niet gelijk is dient er wat afgesneden te worden
- Gemakkelijk in gebruik, waaronder de afbeelding extensie niet op te hoeven geven
- Eventueel meerdere formaten miniaturen te maken, dus een bestandsnaam met de grootte erin zodat deze niet overschreven worden
Dit heeft het volgende resultaat opgeleverd:
<?php
/**
* Create thumbnail (resize and/or crop image)
* @param string $image Source image
* @param integer $width Thumbnail width
* @param integer $height Thumbnail height
* @return string The generated thumbnail
*/
function thumb($image,$width = 200,$height = 200)
{
// Image set?
if($image)
{
// Get the file information
$fileinfo = pathinfo($image);
// Set the thumbnail location
$image_thumb = $fileinfo['dirname'] . '/thumb/' . $width . '-' . $fileinfo['basename'];
// Thumbnail already exists?
if(!file_exists($image_thumb))
{
// Get source as image
$image = imagecreatefromstring(file_get_contents($image));
// Set new size
$thumb_width = $width;
$thumb_height = $height;
// Get image size
$width = imagesx($image);
$height = imagesy($image);
// Calculate ratio
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
// Image wider than new size?
if ( $original_aspect >= $thumb_aspect )
{
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
// New size wider than the image
else
{
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
// Create new image
$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
0, 0,
$new_width, $new_height,
$width, $height);
// Create and return image
imagejpeg($thumb,$image_thumb);
// Destroy
imagedestroy($thumb);
}
// Return the thumbnail
return $image_thumb;
}
else
{
// Set a placeholder
return 'http://placehold.it/'.$width.'x'.$height;
}
}
?>
Tevens wordt er al gecontroleerd of de miniatuur al gemaakt is, hierdoor kan deze eventueel direct aangesproken worden door de functie te koppelen aan GET variabelen:
<?php
if($_GET['thumb'])
{
echo thumb($_GET['thumb'],200,200);
}
?>
Wat vervolgens op de volgende manier gebruikt kan worden:
<img src="file.php?thumb=source-image.jpg" alt="">
Deze functie wordt onder andere gebruikt in een advertentie systeem en op Fastr, een nieuw platform voor autoliefhebbers!