Categories: Development

Resize an image in Vanilla PHP

Here is a way to resize images in PHP without needing a framework like ImageMagick or GD

The below code is derived from here. With the function resize_image taking into account the original image width and height (ratio) to then follow that ratio in your resized image.

 $r) {
        $newwidth = $h * $r;
        $newheight = $h;
    } else {
        $newheight = $w / $r;
        $newwidth = $w;
    }
    //Get the file extension
    $file_type = end(explode(".", $file));
    switch ($file_type) {
        case "png":
            $src = imagecreatefrompng($file);
            break;
        case "jpeg":
        case "jpg":
            $src = imagecreatefromjpeg($file);
            break;
    }
    //create a blank image and then copies over the new resized image
    $out = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($out, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return $out;
}


//image to be resized
$filename = "original.png";
//save new resized image as
$save_as = "resized.png";
// resize the image with 600x600
$imgData = resize_image($filename, 600, 600);
//saves the image
imagepng($imgData, $save_as);

All you need to change is the input, output image name and the resize dimensions.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago