Home > Backend Development > PHP Tutorial > How to Maintain Image Aspect Ratio When Cropping Images in PHP?

How to Maintain Image Aspect Ratio When Cropping Images in PHP?

Patricia Arquette
Release: 2024-11-03 16:46:03
Original
527 people have browsed it

How to Maintain Image Aspect Ratio When Cropping Images in PHP?

Image Cropping in PHP

When cropping images in PHP, you may encounter problems, especially when dealing with large images. One workaround is to "shrink the image".

In the given example code, the image is cropped to a fixed size (200x150), which may not fit larger images. To obtain consistent image dimensions before cropping, it is recommended to use the imagecopyresampled() function.

The following formula can be used to generate thumbnails:

$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 )
{
    // 图像更宽(纵横比意义上)
    $new_height = $thumb_height;
    $new_width = $width / ($height / $thumb_height);
}
else
{
    // 缩略图更宽
    $new_width = $thumb_width;
    $new_height = $height / ($width / $thumb_width);
}

$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );

// 调整大小并裁剪
imagecopyresampled($thumb,
    $image,
    0 - ($new_width - $thumb_width) / 2, // 水平居中图像
    0 - ($new_height - $thumb_height) / 2, // 垂直居中图像
    0, 0,
    $new_width, $new_height,
    $width, $height);
imagejpeg($thumb, $filename, 80);
Copy after login

This code takes the image aspect ratio into account, ensuring that the resized image has the same aspect ratio as the thumbnail size, thus preventing distortion . After resizing and cropping, it will produce a consistently sized image regardless of the original image size.

The above is the detailed content of How to Maintain Image Aspect Ratio When Cropping 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