InvoiceBerry Blog

Convert PNG and GIF pictures to JPEG pictures with PHP

Convert GIF and PNG files into JPEG files with PHP

Convert GIF and PNG files into JPEG files with PHP

A lot of websites offer users to upload avatars, company logos or maybe just a picture that the user has taken. The most common picture formats are normally JPEG, PNG and GIF.

But how can you convert a GIF or PNG image from one of your website visitors into a JPEG image to store it on your webserver?

Try our online invoicing software for free

Send professional-looking invoices
Accept online payments with ease
Keep track of who's paid you

Start sending invoices

Below is a short and easy guide to convert PNG and GIF images into the JPEG format with the help of PHP.

First, set a directory where the image should be stored and find out the file extension:

 //directory where your uploaded files are stored
 $uploads_directory = "/your/directory/where/you/want/to/save/your/images/"

//check extension of the file
 $str = $_FILES['file']['name'];
 $i = strrpos($str,".");
 if (!$i) { $BAD .= "An error occured."; }
 $l = strlen($str) - $i;
 $ext = substr($str,$i+1,$l);

//directory + file name of the image
 $upload_filename = $uploads_directory. "new_image.". $ext  ;

 

Then run the following code if the file extension is PNG or GIF:

//check file extension
 if ($ext == "png" || $ext == "gif"){

//new file name once the picture is converted
 $converted_filename = $uploads_directory. "new_converted_image.jpg";

if ($ext=="png") $new_pic = imagecreatefrompng($upload_filename);
 if ($ext=="gif") $new_pic = imagecreatefromgif($upload_filename);

// Create a new true color image with the same size
 $w = imagesx($new_pic);
 $h = imagesy($new_pic);
 $white = imagecreatetruecolor($w, $h);

// Fill the new image with white background
 $bg = imagecolorallocate($white, 255, 255, 255);
 imagefill($white, 0, 0, $bg);

// Copy original transparent image onto the new image
 imagecopy($white, $new_pic, 0, 0, 0, 0, $w, $h);

$new_pic = $white;

imagejpeg($new_pic, $converted_filename);
 imagedestroy($new_pic);

}

 

Let us know if you need any help implementing this feature on your website. One of our web developers will be happy to help you!

Exit mobile version