Home > Backend Development > PHP Tutorial > How Can I Resize Images in PHP Using GD?

How Can I Resize Images in PHP Using GD?

Patricia Arquette
Release: 2024-12-18 16:49:10
Original
642 people have browsed it

How Can I Resize Images in PHP Using GD?

Resizing Images with PHP

When dealing with images in PHP, you may encounter a need to resize them automatically. This article will guide you through the process, helping you add resize functionality to your image upload script.

To resize images in PHP, you can utilize either ImageMagick or GD functions. GD, being widely available on most web hosting platforms, offers a straightforward method for image manipulation.

Consider the following function for resizing an image using GD:

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}
Copy after login

To use this function, simply invoke it as follows:

$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
Copy after login

Based on personal experience, GD's image resampling notably reduces file size, particularly when processing raw digital camera images.

The above is the detailed content of How Can I Resize Images in PHP Using GD?. 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