Upload, Resize and Save Image in jpg using PHP

June 05, 2012 // In: PHP, Web Design
Some time we need to upload, resize and save images in jpg format. we can do this very easily.

Lets start,
Create a file function.php and place the following code in the file.

<?php
function uploadPicture($img,$filename,$filepath, $Size)
{
$file = $_FILES[$img]['name'];
if ($file != ""){
$path_parts = pathinfo($file);
$extension=$path_parts['extension'];
$filename_path=$filepath.$filename.".jpg";
$destination_path=$filename_path;
if(strtolower($extension)=="jpg" || strtolower($extension)=="jpeg")
{
$uploadedfile = $_FILES[$img]['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if(strtolower($extension) == "png")
{
$uploadedfile = $_FILES[$img]['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$uploadedfile = $_FILES[$img]['tmp_name'];
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth = $Size['width'];
$newheight = $Size['height'];
if ($width <= $newwidth && $height<= $newheight)
{
$newwidth=$width;
$newheight=$height;
$tmp=imagecreatetruecolor($width,$height);
}
else
{
if ($width > $height)
{
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
}else{
$newwidth=($width/$height)*$newheight;
$tmp=imagecreatetruecolor($newwidth,$newheight);
}
}
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
imagejpeg($tmp,$destination_path,100);
imagedestroy($src);
imagedestroy($tmp);
ob_flush();
flush();
ob_end_flush();
return true;
}else{
return false;
}
}
?>

Now create upload.php file and place this code in the file

<?php
require "function.php";
if (isset($_FILES['img1']))
{
$filename = "here_is_file_name";
$filepath = "images/";
$size['width'] = 650;
$size['height'] = 200;
$pic = uploadPicture('img1',$filename, $filepath, $size);
}
?>
<!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=utf-8" />
<title>Upload Image by Sharp Coders</title>
</head>
<body> <form action="post_order.php" name="frmNewOrder" method="post" enctype="multipart/form-data">
Picture <input type="file" name="img1" id="img1" />
<button type="submit" id="submit">Submit</button>
</form>
<br/><br/><br/>
<a href="http://sharp-coders.com" target="_blank">http://sharp-coders.com</a>
</body>
</html>

Submit form using ajax without refreshing page
How to Create Glowing Button in CSS3