Convert Image Format In PHP (WEBP JPG PNG GIF)

Welcome to a tutorial on how to convert the image file format in PHP – From JPG to WEBP, from PNG to JPG, from PNG to WEBP, and whatever else.

To convert JPG to WEBP in PHP:

  • Open the original image – $img = imagecreatefromjpeg("IMG.JPG");
  • Set the color palette – imagepalettetotruecolor($img);
  • Convert and save the image – imagewebp($img, "IMG.WEBP");

That’s all, 3 lines of code. To convert the other file formats, simply open/save the image using their respective functions –

  • imagecreatefromjpeg() imagejpeg()
  • imagecreatefrompng() imagepng()
  • imagecreatefromgif() imagegif()
  • imagecreatefromwebp() imagewebp()
  • imagecreatefrombmp() imagebmp()

That covers the basics, but read on for more examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Please make sure that extension = gd is enabled in php.ini.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

PHP CONVERT IMAGE

The introduction covered the basics, here are a few more examples that may be useful.

 

1) MASS CONVERT THE ENTIRE FOLDER

1-mass-convert.php
<?php
// (A) SETTINGS
$dir = __DIR__ . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR;
$convert = "*.{bmp,jpg,png,gif}"; // glob brace, image types to convert
$valid = ["bmp", "jpg", "jpeg", "png", "gif", "webp"];
 
// (B) CONVERT IMAGE FILES TO WEBP
foreach (glob("$dir$convert", GLOB_BRACE) as $file) {
  // (B1) CHECK VALID IMAGE
  $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  if (!in_array($ext, $valid)) { continue; }
 
  // (B2) "SAVE AS" FILE NAME
  $name = pathinfo($file, PATHINFO_FILENAME);
  $saveas = "$name.webp";
  // do not override existing - remove this to override
  if (file_exists("$dir$saveas")) { continue; }
 
  // (B3) CONVERT IMAGE
  if ($ext=="jpg") { $ext = "jpeg"; }
  $fn = "imagecreatefrom$ext";
  $img = $fn($file);
  imagepalettetotruecolor($img);
  imagewebp($img, "$dir$saveas", 70);
  imagedestroy($img);
  // unlink($file); // remove original if you want
  echo "$dir$saveas - OK";
}

This example will scan the images/ folder for all bmp jpg jpeg png gif files and convert them into webp.

  1. The target folder, files to convert, and the list of valid images.
  2. Extracts a list of images and convert them.
    • (B1) Some may think a “valid image check” is irrelevant, but my line of thought is – PHP GD only supports certain image types, a check against the supported images in $valid is necessary.
    • (B2) “Save as” file name. Yes, remove that file_exists() check if you want to override previously convert files.
    • (B3) As in the introduction – Open the image, save as webp.

 

 

2) UPLOAD & CONVERT

2A) HTML UPLOAD FORM

2a-upload-convert.html
<form action="2b-upload-convert.php" enctype="multipart/form-data"
      method="post" target="_blank">
  <input type="file" name="up" required accept=".jpg,.jpeg,.png,.gif,.bmp">
  <input type="submit" value="Upload">
</form>

This is a simple file upload form. If you want “fancy uploads”, I will leave a few links below.

 

2B) PHP CONVERT UPLOADED IMAGE FILE

2b-upload-convert.php
<?php
// (A) SETTINGS & VARIABLES
$valid = ["bmp", "jpg", "jpeg", "png", "gif", "webp"];
$dir = __DIR__ . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR;
$name = pathinfo($_FILES["up"]["name"], PATHINFO_FILENAME);
$ext = strtolower(pathinfo($_FILES["up"]["name"], PATHINFO_EXTENSION));
$saveto = $dir . $_FILES["up"]["name"];
if ($ext != "webp") { $saveas = "$dir$name.webp"; }
 
// (B) MOVE UPLOADED FILE TO IMAGES FOLDER - ONLY IF VALID
if (!in_array($ext, $valid)) { exit("INVALID IMAGE"); }
  move_uploaded_file(
  $_FILES["up"]["tmp_name"],
  $dir . $_FILES["up"]["name"]
);
 
// (C) CONVERT IF NEEDED
if ($ext != "webp") {
if ($ext=="jpg") { $ext = "jpeg"; }
  $fn = "imagecreatefrom$ext";
  $img = $fn($saveto);
  imagepalettetotruecolor($img);
  imagewebp($img, $saveas, 70);
  imagedestroy($img);
  // unlink($dir . $_FILES["up"]["name"]); // delete original if you want
}
 
// (D) WHAT'S NEXT?
// REDIRECT TO ANOTHER PAGE?
// SHOW AN "UPLOAD OK PAGE"?
// SIMPLE MESSAGE?
echo "OK";

Don’t be intimidated… We are pretty much doing the same “open image and save” here, but only on the uploaded file.

  1. Settings – Where to save the uploaded file to, what is the uploaded file name, extension, etc…
  2. Move the uploaded file, only if it is a valid image.
  3. Convert the image if it is not webp. Pretty much the same as the introduction snippet.
  4. What to do after the conversion.

 

 

EXTRA BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

COMPATIBILITY CHECKS

Works on all modern “Grade A” browsers.

 

LINKS & REFERENCES

 

 

INFOGRAPHIC CHEAT SHEET

Convert Image File Formats In PHP (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

2 thoughts on “Convert Image Format In PHP (WEBP JPG PNG GIF)”

Leave a Comment

Your email address will not be published. Required fields are marked *