InvoiceBerry Blog

Small Business | Invoicing | Marketing | Entrepreneurship | Freelancing

Convert PNG and GIF pictures to JPEG pictures with PHP

Written by on May 14, 2012

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!

The Ultimate Social Media Tool

Download our free guide to learn how to create shareable content, generate website traffic & increase conversions.

Ready to start invoicing your clients with InvoiceBerry?

Sign up to our free trial account. No credit card required.

Sign Up Now
Read previous post:
Best Bank accounts for start-ups and small businesses

Finding the right bank account for your start-up or small business can be harder than you expect. All the major...

Close
We use cookies to give you a better experience. Check out our privacy policy for more information.
OK