/ Published in: PHP
Will create a thumnail no taller or wider than the supplied size. Also contains some tips for reading and writing images using GD.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Create a thumbnail image from $inputFileName no taller or wider than * $maxSize. Returns the new image resource or false on error. * Author: mthorn.net */ function thumbnail($inputFileName, $maxSize = 100) { // Check support of file type { // Server does not support file type return false; } // Calculate aspect ratio $wRatio = $maxSize / $width; $hRatio = $maxSize / $height; // Using imagecreatefromstring will automatically detect the file type // Calculate a proportional width and height no larger than the max size. if ( ($width <= $maxSize) && ($height <= $maxSize) ) { // Input is smaller than thumbnail, do nothing return $sourceImage; } elseif ( ($wRatio * $height) < $maxSize ) { // Image is horizontal $tWidth = $maxSize; } else { // Image is vertical $tHeight = $maxSize; } if ( $sourceImage === false ) { // Could not load image return false; } // Copy resampled makes a smooth thumbnail return $thumb; } /** * Save the image to a file. Type is determined from the extension. * $quality is only used for jpegs. * Author: mthorn.net */ function imageToFile($im, $fileName, $quality = 80) { { return false; } switch ( $ext ) { case '.gif': break; case '.jpg': case '.jpeg': break; case '.png': break; case '.bmp': break; default: return false; } return true; } $im = thumbnail('temp.jpg', 100); imageToFile($im, 'temp-thumbnail.jpg');