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
Patricia ArquetteOriginal
2024-12-18 16:49:10732browse

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;
}

To use this function, simply invoke it as follows:

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

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!

Statement:
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