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. This tutorial a continuation of my previous post, I just included image re-sizing function for different dimensions. It is very useful for your web project that saves lots of hosting space and bandwidth limit. Take a quick look at the live demo.
Download Script Live Demo
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
-- getExtension.php
-- compressImage.php
js
-- jquery.min.js
-- jquery.form.js
uploads
index.php
ajaximageupload.php
db.php
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" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('body').on('change','#photoimg', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('body').on('change','#photoimg', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
Note: For multiple image uploads, use jquery.wallform.js instead of jquery.form.js which is available inside download script.
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>
Sample database design for Users.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>
Users
Contains user details username, password, email and profile_image etc.
CREATE TABLE `users` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200)
)
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY,
`profile_image` varchar(200)
)
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,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;
}
?>
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,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;
}
?>
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;
}
{
$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);
?>
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);
?>
thanks
ReplyDeleteNice article, Mime-type security??
ReplyDeleteWill it support multiple file( in separate input fields ) uploads?
ReplyDeleteNIce !
ReplyDeletegetExtension => very basic function...
(with no tolerance of using a "." in the name itself, for example...)
How about using some regular expression for something more powerfull/robust?
Something like :
function getExtension($str)
{
if (preg_match('/\.[a-zA-Z0-9]{2,4}$/i', $str, $matches)) {
return $matches[0];
}else{
return '';
}
good tutorial.
ReplyDeletemay I request.
how about compress image using php imagic
I'm getting an error :
ReplyDelete[jquery.form] state = complete jquery.form.js:904
[jquery.form] isXml=false jquery.form.js:904
U have grown weight my friend... :))
ReplyDeleteFor multiple image uploads, use jquery.wallform.js instead of jquery.form.js which is available inside download script.
ReplyDeleteMan,live function is already deprecated since Jquery 1.7 !
ReplyDeleteModified .live to on, please update this in your download script.
ReplyDeleteNice Script. It works !
ReplyDeletenice post..
ReplyDeleteit really works...
thanks
somehow resized png images have black background. It seems that it is not working. Any ideas.
ReplyDeleteI fıxed ıt change the compressImage functıon
ReplyDelete//Compress Image
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);
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
$trans_layer_overlay = imagecolorallocatealpha($tmp, 220, 220, 220, 127);
imagefill($tmp, 0, 0, $trans_layer_overlay);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $path.$newwidth.'_'.$actual_image_name;
if($ext=="jpg" || $ext=="jpeg" )
{
imagejpeg($tmp,$filename,100);
}
else if($ext=="png")
{
imagepng($tmp,$filename);
}
else
{
imagegif($tmp,$filename);
}
imagedestroy($tmp);
return $filename;
}
Good examples but very low php skills...most of scripts here are very unsecured (ok, it's only examples).
ReplyDeleteHowever, about file extension, simply use this:
$ext = pathinfo($FilePath, PATHINFO_EXTENSION);
mysql_connect is (or it will be) deprecated. Switch to PDO...
This comment has been removed by the author.
ReplyDeletei am trying to import the details to my sql database
ReplyDeleteplease whats the problem
this the database [ CREATE TABLE `img` (
`uid` int(11) AUTO_INCREMENT PRIMARY KEY,
`profile_image` varchar(200)
)
]
ajax code [ mysqli_query($db,"INSERT INTO img(uid,profile_image)
VALUES('$session_id''$image_name',)");
]
THANKS YOU
nice
ReplyDeleteThat's interesting! Yours scripts would really be helpful to save lots of time for developers.
ReplyDeleteThank you so much dude!!
ReplyDeleteHow can i upload an image more than 1MB...when i am trying to upload more than 1MB it is showing like this errors.......
ReplyDeleteWarning: Division by zero in C:\wamp\www\resize\includes\compressImage.php on line 23
Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\wamp\www\resize\includes\compressImage.php on line 24
Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 25
Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 27
Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 28
Warning: Division by zero in C:\wamp\www\resize\includes\compressImage.php on line 23
Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\wamp\www\resize\includes\compressImage.php on line 24
Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 25
Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 27
Warning: imagedestroy(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 28
Warning: Division by zero in C:\wamp\www\resize\includes\compressImage.php on line 23
Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\wamp\www\resize\includes\compressImage.php on line 24
Warning: imagecopyresampled(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 25
Warning: imagejpeg(): supplied argument is not a valid Image resource in C:\wamp\www\resize\includes\compressImage.php on line 27
So can you please help me out of this.
For Multiple file upload...Beside adding jquery.wallform.js... do i need to code in php or html ?
ReplyDeleteThe best script it work done, thanks you
ReplyDeletehow to crop to center size instead of resize the width only?
ReplyDeleteAwesome ! and really useful understanding...
ReplyDeleteso this is the script i have been looking for and now i have to wait 18 hours to download it... not very convenient
ReplyDeletethat's what i want .......
ReplyDeleteit's awesome
thanx for sharing............
Very nice Job
ReplyDeleteThank you for sharing...
I do the necessary changes in code but when i upload an image only address is visible in the div. Image is not uploading....
ReplyDeletePlease Help
helpffull script, tq how to delete image?
ReplyDeleteVery nice script, but this for multiple uploads I can't get this to work....
ReplyDelete"Note: For multiple image uploads, use jquery.wallform.js instead of jquery.form.js which is available inside download script. "
Thank you very much. Very nice and easy script.
ReplyDeleteHello, I have been subscribed for over 24 hours and still receiving message: "Sorry no email found subscribe below"
ReplyDeleteThanks
ReplyDeleteHow can I specify width and height of all three vesions seperately?(I do not want have square versions!)
same here
DeleteThanks very much
ReplyDeleteI need to specify height also. I don't want square size. What can I do?
Broken link as of now...
ReplyDeletecan we add delete button to upload image and how??
ReplyDeleteI am trying to adapt this script so that I can upload an image then resize then insert into blob in mysqli with php, how can this script be modded so that the uploaded file is resized and inserted without creating an extra temporary file.
ReplyDeleteThis is really wonderful! I have adapted it for my site.
ReplyDeletesuper
ReplyDeletepng image size to big
ReplyDeletepng image not compress give solution
ReplyDelete