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!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

PHP CONVERT IMAGE

All right, let us now get into more detailed examples of converting the image format in PHP.

 

TUTORIAL VIDEO

 

1) CONVERT SINGLE IMAGE

1-single.php
<?php
// (A) IMAGE CONVERT FUNCTION
function imgcon ($from, $to, $quality=null) {
  // (A1) CHECK VALID IMAGE TYPE
  $extf = strtolower(pathinfo($from, PATHINFO_EXTENSION));
  $extt = strtolower(pathinfo($to, PATHINFO_EXTENSION));
  $valid = ["bmp", "jpg", "jpeg", "png", "gif", "webp"];
  if (!in_array($extf, $valid) || !in_array($extt, $valid)) { return false; }
 
  // (A2) PROCESS CONVERSION
  if ($extf=="jpg") { $extf = "jpeg"; }
  if ($extt=="jpg") { $extt = "jpeg"; }
  $fnf = "imagecreatefrom$extf";
  $fnt = "image$extt";
  $img = $fnf($from);
  imagepalettetotruecolor($img);
  if ($quality !== null) { $fnt($img, $to, $quality); } else { $fnt($img, $to); }
  imagedestroy($img);
  // unlink($from); // delete source image if you want
  return true;
}
 
// (B) GO!
echo imgcon("ONE.jpg", "DEMOA.webp") ? "OK" : "ERROR" ;

This simple function pretty much does the same thing as the introduction snippet. Except that it is much more convenient – It “detects” the extensions and automatically calls the respective imagecreatefromX() and imageY().

 

 

2) MASS CONVERT THE ENTIRE FOLDER

2-mass.php
<?php
// (A) SETTINGS
$cdir = __DIR__ . DIRECTORY_SEPARATOR; // convert all images in this folder
$cto = "webp"; // convert to this format
$cqy = null; // convert quality, null to use default
 
// (B) CONVERT IMAGE FILES
$clist = array_diff(["bmp", "jpg", "jpeg", "png", "gif", "webp"], [$cto]);
$clist = "$cdir*.{" . implode(",", $clist) . "}";
foreach (glob($clist, GLOB_BRACE) as $file) {
  // (B1) "SAVE AS" FILE NAME
  $saveas = $cdir . pathinfo($file, PATHINFO_FILENAME) . ".$cto";
  if (file_exists($saveas)) { continue; } // do not overwrite
 
  // (B2) PROCESS CONVERSION
  $extf = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  if ($extf=="jpg") { $extf = "jpeg"; }
  $extt = $cto=="jpg" ? "jpeg" : $cto ;
  $fnf = "imagecreatefrom$extf";
  $fnt = "image$extt";
  $img = $fnf($file);
  imagepalettetotruecolor($img);
  if ($cqy !== null) { $fnt($img, $saveas, $cqy); }
  else { $fnt($img, $saveas); }
  imagedestroy($img);
  // unlink($file); // delete source image if you want
  echo "$saveas - OK";
}

If you need to convert an entire folder, here is a snippet that will help.

  • (A) Define the target folder and what image format you want.
  • (B) We use glob() to fetch a list of all the images and loop through them.
  • (B1 & B2) The same old “detect extension and convert automatically”.

 

 

3) UPLOAD & CONVERT

3A) HTML UPLOAD FORM

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

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

 

3B) PHP CONVERT UPLOADED IMAGE FILE

3b-upload.php
<?php
// (A) SETTINGS
$cdir = __DIR__ . DIRECTORY_SEPARATOR . "test" . DIRECTORY_SEPARATOR; // save to this directory
$cto = "webp"; // convert to this format
$cqy = null; // convert quality, null to use default
 
// (B) CHECK UPLOADED FILE
$ext = strtolower(pathinfo($_FILES["up"]["name"], PATHINFO_EXTENSION));
if (!in_array($ext, ["bmp", "jpg", "jpeg", "png", "gif", "webp"])) { exit("INVALID IMAGE"); }
 
// (C) MOVE UPLOADED FILE
$saveto = $cdir . $_FILES["up"]["name"];
move_uploaded_file($_FILES["up"]["tmp_name"], $saveto);
 
// (D) CONVERT IF NEEDED
if ($ext != $cto) {
  $extf = $ext=="jpg" ? "jpeg" : $ext ;
  $extt = $cto=="jpg" ? "jpeg" : $cto ;
  $saveas = $cdir . pathinfo($saveto, PATHINFO_FILENAME) . ".$cto";
  $fnf = "imagecreatefrom$extf";
  $fnt = "image$extt";
  $img = $fnf($saveto);
  imagepalettetotruecolor($img);
  if ($cqy !== null) { $fnt($img, $saveas, $cqy); }
  else { $fnt($img, $saveas); }
  imagedestroy($img);
  // unlink($saveto); // delete source image if you want
}
 
// (E) 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 old “open image and save” here, but only on the uploaded file.

  1. Settings – Where to save the uploaded file and what format you need.
  2. Check if the uploaded file is a valid image.
  3. Save the source image.
  4. Convert the image if required.
  5. What to do after the upload/conversion.

 

 

EXTRAS

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

 

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 *