Convert Image to JPG, PNG & GIF in PHP

php-img-converter

Here I’m coming up with a new PHP class, which will help you to convert any uploaded image to JPG, PNG and GIF.

Class name: image_converter.php

<?php 

/***
*	Image converter Script by Agurchand 
*	Find the script at Theonlytutorials.com	
*
* 	convert_image() has 3 mandatory parameters
*	$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'
*
*	//optional parameter
*	$image_quality 	=> can be adjusted, if you don't want 100% quality
*
*	upload_image() is the upload image handler, if you don't have an upload script, you can use this!
*	
*	you can edit this script as per your requirement
* 	if you are going to re-produce the script, please mention the original script from 'theonlytutorials.com'
***/


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;
	}
}
?>

See the Demo or Download the PHP image converter script here:

 demodownload

 

 

Converter Function in the Image_converter class is:

//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; 
	}

convert_image() has 3 mandatory parameters
* $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’
*
* //optional parameter
* $image_quality => can be adjusted, if you don’t want 100% quality

Here is the complete usage of the above PHP class, which includes image upload and image conversion script.

index.php – Uploads 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: lightgray;
	}
	table{
		margin-top: 200px;
		background: white;
	}
</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="500" align="center">
		<tr><td align="center">	<h2 align="center">Image Uploader & Converter by Theonlytutorials.com</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>

 convert.php – Converts the image.

<?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>

 download.php – 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); 

?>

Enjoy the Day!

9 thoughts on “Convert Image to JPG, PNG & GIF in PHP

  1. Hi, thanks for sharing,
    How can I convert a image file that is already on my server? I was trying to do something like this
    $image = $obj->convert_image(‘jpg’, $target_dir, $path_to_my_image);
    But is not working, any help would be great.

    1. Hi,
      $target_dir => should be the path of the image without the image name.
      $image_name => name of the image you want get and save as

      If you read the article, i have mentioned $target_dir is the source of the image as well as target path.
      So in your case, you should give like below;
      let’s assume your image is in some folder: /var/www/html/yourfolder/image/yourimage.jpg

      you should give the values this way,

      $target_dir = ‘/var/www/html/yourfolder/image/’;
      $image_name = ‘yourimage.jpg’;

      $image = $obj->convert_image(‘jpg’, $target_dir, $image_name);

      thanks,
      Agurchand

  2. It is not working in localhost.
    Fatal error : undefined imagecreatefromstring function is showing.

    please help how can I run it in my computer.

Leave a Reply

Theme: Overlay by Kaira
Agurchand