Ajax Upload and Resize an Image with PHP.
Wall Script
Follow Me:
Thursday, July 31, 2014

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

 Ajax Upload and Resize an Image with PHP.


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

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.

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.

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


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

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);
?>
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


39 comments:

  1. Nice article, Mime-type security??

    ReplyDelete
  2. Will it support multiple file( in separate input fields ) uploads?

    ReplyDelete
  3. NIce !

    getExtension => 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 '';
    }

    ReplyDelete
  4. good tutorial.
    may I request.
    how about compress image using php imagic

    ReplyDelete
  5. I'm getting an error :

    [jquery.form] state = complete jquery.form.js:904
    [jquery.form] isXml=false jquery.form.js:904

    ReplyDelete
  6. U have grown weight my friend... :))

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

    ReplyDelete
  8. Man,live function is already deprecated since Jquery 1.7 !

    ReplyDelete
  9. Modified .live to on, please update this in your download script.

    ReplyDelete
  10. nice post..
    it really works...
    thanks

    ReplyDelete
  11. somehow resized png images have black background. It seems that it is not working. Any ideas.

    ReplyDelete
  12. I fıxed ıt change the compressImage functıon

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

    ReplyDelete
  13. Good examples but very low php skills...most of scripts here are very unsecured (ok, it's only examples).

    However, about file extension, simply use this:
    $ext = pathinfo($FilePath, PATHINFO_EXTENSION);

    mysql_connect is (or it will be) deprecated. Switch to PDO...

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. i am trying to import the details to my sql database
    please 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

    ReplyDelete
  16. That's interesting! Yours scripts would really be helpful to save lots of time for developers.

    ReplyDelete
  17. How can i upload an image more than 1MB...when i am trying to upload more than 1MB it is showing like this errors.......

    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

    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.

    ReplyDelete
  18. For Multiple file upload...Beside adding jquery.wallform.js... do i need to code in php or html ?

    ReplyDelete
  19. The best script it work done, thanks you

    ReplyDelete
  20. how to crop to center size instead of resize the width only?

    ReplyDelete
  21. Awesome ! and really useful understanding...

    ReplyDelete
  22. so this is the script i have been looking for and now i have to wait 18 hours to download it... not very convenient

    ReplyDelete
  23. that's what i want .......
    it's awesome

    thanx for sharing............

    ReplyDelete
  24. Very nice Job
    Thank you for sharing...

    ReplyDelete
  25. I do the necessary changes in code but when i upload an image only address is visible in the div. Image is not uploading....
    Please Help

    ReplyDelete
  26. helpffull script, tq how to delete image?

    ReplyDelete
  27. Very nice script, but this for multiple uploads I can't get this to work....
    "Note: For multiple image uploads, use jquery.wallform.js instead of jquery.form.js which is available inside download script. "

    ReplyDelete
  28. Thank you very much. Very nice and easy script.

    ReplyDelete
  29. Hello, I have been subscribed for over 24 hours and still receiving message: "Sorry no email found subscribe below"

    ReplyDelete
  30. Thanks
    How can I specify width and height of all three vesions seperately?(I do not want have square versions!)

    ReplyDelete
  31. Thanks very much
    I need to specify height also. I don't want square size. What can I do?

    ReplyDelete
  32. can we add delete button to upload image and how??

    ReplyDelete
  33. I 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.

    ReplyDelete

Make in India