Ajax Upload and Resize an Image with PHP

Today I am presenting the most important social networking feature called ajax upload and resize an image without refreshing the page using jquery and PHP. It is very useful for your web project that saves lots of hosting space and bandwidth limit.

The tutorial contains three folders called js,includes and uploads with PHP files.

includes
getExtension.php 
compressImage.php
js
jquery.min.js
jquery.form.js
uploads
index.php
ajaximageupload.php
db.php

index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.

<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image: 
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photoimg" id="photoimg" />

</div>
</form>

Javascript Code
$(“#photoimg”).live(‘change’,function(){})photoimg is the ID name of INPUT FILE tag and $(‘#imageform’).ajaxForm() – imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.

<script type="text/javascript" >
$(document).ready(function() { 
		
$('#photoimg').die('click').live('change', function()	{ 
//$("#preview").html('');
			    
$("#imageform").ajaxForm({target: '#preview', beforeSubmit:function(){ 
				
$("#imageloadstatus").show();
$("#imageloadbutton").hide(); }, 
success:function(){ 
				
$("#imageloadstatus").hide();
$("#imageloadbutton").show(); }, 

error:function(){ 
					
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
					
});
}); 
</script>

Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.

Note: For multiple image uploads, use jquery.wallform.js instead of jquery.form.js which is available inside download script.

CSS

body
{
font-family:arial;
font-size:12px;
}
.preview
{
width:300px;
border:solid 1px #dedede;
padding:6px;
margin-right:10px;
}
.img
{
border:solid 1px #dedede;
padding:6px;
margin-right:10px;
}
#preview
{
font-size:12px;
}

User_images
Contains user details id, image_name, emp_id_fk and created_date  etc.

CREATE TABLE IF NOT EXISTS `user_images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `image_name` int(200) NOT NULL,
  `emp_id_fk` int(11) NOT NULL,
  `created_date` date NOT NULL,
  PRIMARY KEY (`id`)
)

ajaximage.php
Contains PHP code. This script helps you to upload images into uploads folder. Image file name rename into timestamp+session_id.extention

<?php
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";

$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
include_once 'includes/getExtension.php';
$imagename = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($imagename))
{
$ext = strtolower(getExtension($imagename));
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$uploadedfile = $_FILES['photoimg']['tmp_name'];

//Re-sizing image. 
include 'includes/compressImage.php';
$widthArray = array(200,150,100,50); //You can change dimension here.
foreach($widthArray as $newwidth)
{
$filename=compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth);
echo "<img src='".$filename."' class='img'/>";
}

//Original Image
if(move_uploaded_file($uploadedfile, $path.$actual_image_name))
{
//Insert upload image files names into user_uploads table
mysqli_query($db,"UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id';");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>

compressImage.php
Re-sizing image into different pixel dimensions.

<?php
function compressImage($ext,$uploadedfile,$path,$actual_image_name,$newwidth)
{

if($ext=="jpg" || $ext=="jpeg" )
{
$src = imagecreatefromjpeg($uploadedfile);
}
else if($ext=="png")
{
$src = imagecreatefrompng($uploadedfile);
}
else if($ext=="gif")
{
$src = imagecreatefromgif($uploadedfile);
}
else
{
$src = imagecreatefrombmp($uploadedfile);
}

list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $path.$newwidth.'_'.$actual_image_name; //PixelSize_TimeStamp.jpg
imagejpeg($tmp,$filename,100);
imagedestroy($tmp);
return $filename;
}
?>

getExtension.php
This extracts file extension.

function getExtension($str)
{
$i = strrpos($str,".");
if (!$i)
{
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

db.php
Database configuration file, modify username, password and database values.

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

 

 

Please follow and like us:

Add a Comment