Swiss-knife function to resize, crop, convert and save to WebP and Jpeg simultaneously (PHP)

Post Photo
Tuesday, 29th September 2020

Maybe the most used function for media in VerdinCMS. Resize, Crop, Convert, Save and maintain aspect ratios. Tested using thousands of pictures

First of all it loads your image to the $img variable. It supports bmp, gif, jpg, png and webp.

Then it resizes and crops the image in order to maintain the requested aspect ratio.

At the end it saves two copies in WebP and Jpg to your server. Very useful if you use the HTML picture tag for compatibility reasons.

Enjoy!

/**
* Resize Image to WebP & Jpeg
*/

function img_resize($source, $destination, $width=800, $height=450, $quality=75) {
    $extension = strtolower(pathinfo($source, PATHINFO_EXTENSION));
    $jpg_destination = pathinfo($destination, PATHINFO_DIRNAME) . '/' . pathinfo($destination, PATHINFO_FILENAME) . '.jpg';

switch($extension){
    case 'bmp' : $img = imagecreatefromwbmp($source); break;
    case 'gif' : $img = imagecreatefromgif($source); break;
    case 'jpg' : $img = imagecreatefromjpeg($source); break;
    case 'jpeg': $img = imagecreatefromjpeg($source); break;
    case 'png' : $img = imagecreatefrompng($source); break;
    case 'webp': $img = imagecreatefromwebp($source); break;
    default : return "Unsupported picture type!";
}

$source_ratio = imagesx($img) / imagesy($img);
$new_ratio = $width / $height;

if( $source_ratio <= $new_ratio) {
    $img = imagescale($img,$width);
    $crop_y = round((imagesy($img) - $height) / 2);
    $img = imagecrop($img, ['x' => 0, 'y' => $crop_y, 'width' => $width, 'height' => $height]);
} else {
    $new_width = round($height * $source_ratio);
    $img = imagescale($img,$new_width,$height);
    $crop_x = round((imagesx($img) - $width) / 2);
    $img = imagecrop($img, ['x' => $crop_x, 'y' => 0, 'width' => $width, 'height' => $height]);
}

imagewebp($img, $destination, $quality);
imagejpeg($img, $jpg_destination, 60);
imagedestroy($img);

}

Share Post

If you like this post please share with your friends