How to Effectively Crop Large Images in PHP?

Susan Sarandon
Release: 2024-11-03 18:49:02
Original
993 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!