Sunday, April 10 2016

How to Upload Image With Custom Resize in PHP

In this article we have explained about how to upload an image with resize using simple php script. Save image as your width and height.

In HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
		<title>Upload Image File and Resized</title>
		<style>
			.success{
				color:green;
			} 
			.error{
				color:red;
			}
		</style>
	</head>
	<body>
		<form enctype="multipart/form-data" action="" method="post">
			<input type="file" name="files" />
			<input type="submit" value="Upload File" name="upload"/>
		</form>
	</body>
</html>

In PHP:

<?php
if(isset($_REQUEST['upload'])){
	$file_name = strtolower($_FILES['files']['name']);
	$uploadedfile = $_FILES['files']['tmp_name'];
	$src = imagecreatefromjpeg($uploadedfile);
	list($width,$height)=getimagesize($uploadedfile);
	$newwidth=250;
	// $newheight=250;
	$newheight=($height/$width)*$newwidth;
	$tmp=imagecreatetruecolor($newwidth,$newheight);
	imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
	$filename = "uploads/thumb/". $_FILES['files']['name'];
	imagejpeg($tmp,$filename,3000);
	$result = move_uploaded_file($_FILES['files']['tmp_name'], 'uploads/large/'.$file_name);	
	if($result){
		echo '<p class="success"> Image uploaded and resized successfully.</p>';
	} else {
		echo '<p class="error"> Image can\'t upload and resized.</p>';
	}
}
?>

 

Share Your Thoughts

phpexpertise

I’m Blogger and Programming Blog, Tutorials, PHP, MySQL, jQuery, Laravel, Wordpress and Codeigniter