Skip to content

Instantly share code, notes, and snippets.

@johnroyer
Last active December 7, 2021 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnroyer/85d0631d175b85a7befa3714855f4ab9 to your computer and use it in GitHub Desktop.
Save johnroyer/85d0631d175b85a7befa3714855f4ab9 to your computer and use it in GitHub Desktop.
Simple PHP script to convert jpeg / gif / png to webp

Introduction

Using PHP GD library to covert common type images to webp format.

Guide

Download script:

sudo wget https://gist.githubusercontent.com/johnroyer/85d0631d175b85a7befa3714855f4ab9/raw/3d70527b4c66279eaa97d997f84f1e42a51ccf18/webp.php -O /bin/webp
sudo chmod +x /bin/webp

Usage:

webp image.png NEW_NAME.webp
#!/usr/bin/env php
<?php
$inputFile = $argv[1];
$outputFile = $argv[2];
// check file type
$mime = [
'image/bmp' => 'imagecreatefrombmp',
'image/gif' => 'imagecreatefromgif',
'image/jpeg' => 'imagecreatefromjpeg',
'image/png' => 'imagecreatefrompng',
];
$type = mime_content_type($inputFile);
if (!array_key_exists($type, $mime)) {
echo "un-recognized type: {$type}\n";
exit(255);
}
$img = $mime[$type]($inputFile);
// output webp
imagewebp($img, $outputFile);
imagedestroy($img);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment