Home > Article > Backend Development > How to Create Proportional Thumbnails in PHP for Large Images?
Creating Scaled Thumbnails in PHP
The provided code snippet successfully crops an image within a given dimension. However, for larger images, it may not produce the desired results. To address this issue, it is necessary to first resize the image, ensuring that the smaller dimension of the resized image matches the corresponding dimension of the thumbnail.
To create proportional thumbnails, follow these steps:
Here is an updated code example that implements these steps:
<code class="php">$image = imagecreatefromjpeg($_GET['src']); $filename = 'images/cropped_whatever.jpg'; $thumb_width = 200; $thumb_height = 150; $width = imagesx($image); $height = imagesy($image); $original_aspect = $width / $height; $thumb_aspect = $thumb_width / $thumb_height; if ( $original_aspect >= $thumb_aspect ) { // If image is wider than thumbnail (in aspect ratio sense) $new_height = $thumb_height; $new_width = $width / ($height / $thumb_height); } else { // If the thumbnail is wider than the image $new_width = $thumb_width; $new_height = $height / ($width / $thumb_width); } $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); imagejpeg($thumb, $filename, 80);</code>
By incorporating image resizing into the thumbnail generation process, it is possible to create well-proportioned thumbnails that are independent of the original image size.
The above is the detailed content of How to Create Proportional Thumbnails in PHP for Large Images?. For more information, please follow other related articles on the PHP Chinese website!