🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Image Convert to JPG, PNG & GIF using PHP

In this post I help you to convert any uploaded image to JPG, PNG and GIF.

Create a file image_converter.php.

<?php
class Image_converter{
//image converter
function convert_image($convert_type, $target_dir, $image_name, $image_quality=100){
$target_dir = "$target_dir/";
$image = $target_dir.$image_name;
//remove extension from image;
$img_name = $this->remove_extension_from_image($image);
//to png
if($convert_type == 'png'){
$binary = imagecreatefromstring(file_get_contents($image));
//third parameter for ImagePng is limited to 0 to 9
//0 is uncompressed, 9 is compressed
//so convert 100 to 2 digit number by dividing it by 10 and minus with 10
$image_quality = floor(10 - ($image_quality / 10));
ImagePNG($binary, $target_dir.$img_name.'.'.$convert_type, $image_quality);
return $img_name.'.'.$convert_type;
}
//to jpg
if($convert_type == 'jpg'){
$binary = imagecreatefromstring(file_get_contents($image));
imageJpeg($binary, $target_dir.$img_name.'.'.$convert_type, $image_quality);
return $img_name.'.'.$convert_type;
}
//to gif
if($convert_type == 'gif'){
$binary = imagecreatefromstring(file_get_contents($image));
imageGif($binary, $target_dir.$img_name.'.'.$convert_type, $image_quality);
return $img_name.'.'.$convert_type;
}
return false;
}
//image upload handler
public function upload_image($files, $target_dir, $input_name){
$target_dir = "$target_dir/";
//get the basename of the uploaded file
$base_name = basename($files[$input_name]["name"]);
//get the image type from the uploaded image
$imageFileType = $this->get_image_type($base_name);
//set dynamic name for the uploaded file
$new_name = $this->get_dynamic_name($base_name, $imageFileType);
//set the target file for uploading
$target_file = $target_dir . $new_name;
// Check uploaded is a valid image
$validate = $this->validate_image($files[$input_name]["tmp_name"]);
if(!$validate){
echo "Doesn't seem like an image file :(";
return false;
}
// Check file size - restrict if greater than 1 MB
$file_size = $this->check_file_size($files[$input_name]["size"], 1000000);
if(!$file_size){
echo "You cannot upload more than 1MB file";
return false;
}
// Allow certain file formats
$file_type = $this->check_only_allowed_image_types($imageFileType);
if(!$file_type){
echo "You cannot upload other than JPG, JPEG, GIF and PNG";
return false;
}
if (move_uploaded_file($files[$input_name]["tmp_name"], $target_file)) {
//return new image name and image file type;
return array($new_name, $imageFileType);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
protected function get_image_type($target_file){
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
return $imageFileType;
}
protected function validate_image($file){
$check = getimagesize($file);
if($check !== false) {
return true;
}
return false;
}
protected function check_file_size($file, $size_limit){
if ($file > $size_limit) {
return false;
}
return true;
}
protected function check_only_allowed_image_types($imagetype){
if($imagetype != "jpg" && $imagetype != "png" && $imagetype != "jpeg" && $imagetype != "gif" ) {
return false;
}
return true;
}
protected function get_dynamic_name($basename, $imagetype){
$only_name = basename($basename, '.'.$imagetype); // remove extension
$combine_time = $only_name.'_'.time();
$new_name = $combine_time.'.'.$imagetype;
return $new_name;
}
protected function remove_extension_from_image($image){
$extension = $this->get_image_type($image); //get extension
$only_name = basename($image, '.'.$extension); // remove extension
return $only_name;
}
}
?>

In this code you see using convert_image() has three mandatory parameters like as:

$convert_type => accepts string either png,jpg or gif.
$target_dir => it is the source as well as the target directory
$image_name => give the actual image name such as image1.jpg.
$image_quality => can be adjusted, if you don’t want 100% quality.

Next, create index.php to Upload the image.

<?php
//import the converter class
require('image_converter.php');
if($_FILES){
$obj = new Image_converter();
//call upload function and send the $_FILES, target folder and input name
$upload = $obj->upload_image($_FILES, 'uploads', 'fileToUpload');
if($upload){
$imageName = urlencode($upload[0]);
$imageType = urlencode($upload[1]);
if($imageType == 'jpeg'){
$imageType = 'jpg';
}
header('Location: convert.php?imageName='.$imageName.'&imageType='.$imageType);
}
}
?>
<html>
<head>
<style>
body{
background: white;
}
table{
margin-top: 200px;
background: lightgray;
}
</style>
<script>
function checkEmpty(){
var img = document.getElementById('fileToUpload').value;
if(img == ''){
alert('Please upload an image');
return false;
}
return true;
}
</script>
</head>
<body>
<table width="550" align="center">
<tr><td align="center"> <h2 align="center">Image Upload & Convert by Using PHP</h2></td></tr>
<tr><td align="center"><h4>Convert Any image to JPG, PNG, GIF</h4></td></th>
<tr>
<td align="center">
<form action="" enctype="multipart/form-data" method="post" onsubmit="return checkEmpty()" />
<input type="file" name="fileToUpload" id="fileToUpload" />
<input type="submit" value="Upload" />
</form>
</td>
</tr>
</table>
</body>
</html>
view raw index.php hosted with ❤ by GitHub

Then, create convert.php to convert the image. And make a folder in your directory name as uploads. Because when the image is uploaded or convert, the image will save on this folder.

<?php
//import the converter class
require('image_converter.php');
$imageType = '';
$download = false;
//handle get method, when page redirects
if($_GET){
$imageType = urldecode($_GET['imageType']);
$imageName = urldecode($_GET['imageName']);
}else{
header('Location:index.php');
}
//handle post method when the form submitted
if($_POST){
$convert_type = $_POST['convert_type'];
//create object of image converter class
$obj = new Image_converter();
$target_dir = 'uploads';
//convert image to the specified type
$image = $obj->convert_image($convert_type, $target_dir, $imageName);
//if converted activate download link
if($image){
$download = true;
}
}
//convert types
$types = array(
'png' => 'PNG',
'jpg' => 'JPG',
'gif' => 'GIF',
);
?>
<html>
<head>
<style>
img{
max-width: 360px;
}
body{
background: lightgray;
}
</style>
</head>
<body>
<?php if(!$download) {?>
<form method="post" action="">
<table width="500" align="center">
<tr>
<td align="center">
File Uploaded, Select below option to convert!
<img src="uploads/<?=$imageName;?>" />
</td>
</tr>
<tr>
<td align="center">
Convert To:
<select name="convert_type">
<?php foreach($types as $key=>$type) {?>
<?php if($key != $imageType){?>
<option value="<?=$key;?>"><?=$type;?></option>
<?php } ?>
<?php } ?>
</select>
<br /><br />
</td>
</tr>
<tr>
<td align="center"><input type="submit" value="convert" /></td>
</tr>
</table>
</form>
<?php } ?>
<?php if($download) {?>
<table width="500" align="center">
<tr>
<td align="center">
Image Converted to <?php echo ucwords($convert_type); ?>
<img src="<?=$target_dir.'/'.$image;?>" />
</td>
</tr>
<td align="center">
<a href="download.php?filepath=<?php echo $target_dir.'/'.$image; ?>" />Download Converted Image</a>
</td>
</tr>
<tr>
<td align="center"><a href="index.php">Convert Another</a></td>
</tr>
</table>
<?php } ?>
</body>
</html>

And, create a download.php to downloads the converted image forcefully.

<?php
$file_path = $_GET['filepath'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_path) . "\"");
readfile($file_path);
?>

Then, Run the index.php and see the view.

After Upload the image.

After converted the image.

Then, you can download or convert another image.

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.