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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago