Home > Backend Development > PHP Tutorial > How Can I Resize Uploaded Images to 147x147px in PHP Using GD?

How Can I Resize Uploaded Images to 147x147px in PHP Using GD?

Susan Sarandon
Release: 2024-12-17 05:03:25
Original
940 people have browsed it

How Can I Resize Uploaded Images to 147x147px in PHP Using GD?

Image Scaling in PHP

Case Introduction

In PHP, you want to write some code to pass a form Any images uploaded are automatically resized to 147x147px. You want to reduce the file size by scaling the image.

Code Implementation

To accomplish this task, you can use PHP's ImageMagick or GD functions to process images.

Using GD, you can achieve the following functions:

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

You can call this function as follows:

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

As a rule of thumb, image resampling by GD It does reduce file size significantly, especially when resampling raw digital camera images.

The above is the detailed content of How Can I Resize Uploaded Images to 147x147px 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