Home > Article > Backend Development > How to Effectively Crop Large Images in PHP?
Crop Image in PHP: Resizing for Larger Images
The provided code effectively crops images but may struggle with larger images. To address this, we can "zoom out" of the image. The objective is to maintain consistency in image sizes before cropping, ensuring optimal results.
The key to resizing images for thumbnails is using imagecopyresampled(). The resize operation should adjust the smaller side of the image to match the corresponding side of the thumb. For instance, if the source image is 1280x800px and the thumbnail is 200x150px, the image should be resized to 240x150px before cropping. This ensures that the aspect ratio remains intact.
Here's a revised code using this approach:
<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>
This code resizes the image first, then crops it. By adjusting the resize parameters, you can control the aspect ratio and maintain a consistent size for thumbnails.
The above is the detailed content of How to Effectively Crop Large Images in PHP?. For more information, please follow other related articles on the PHP Chinese website!