- SPLessons

Ajax multiple image upload resize with ...

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Ajax multiple image upload resize with jquery and php

Ajax multiple image upload resize with jquery and php

Description :

Today in this article we are going to explain Ajax multiple image upload resize with jquery and php. We are creating Ajax based image uploaded with the help of form JavaScript library and php. In php we are using Image Processing and Generation API, .In this we have number functions like imagecreatefromjpeg (), imagetruecolor (), imagecopyresampled (), imagejpeg () these functions are used to manipulating the images. In this article we are mainly used bellow functions to manipulate the images.

Step1 :
In step 1 first we bind a change event handler function on Files element. So, every file information is stored in event Object like type, size, name etc.  Now, we bind submit event handler to submit the form but before the submitting the form we validate every files related to types and Sizes. Now, we are create a FormData object to access the all validation files and we send these files to server with the help of Ajax without reloading a page.

Note : In backend  in upload folder  I created three sub folders 200,100,50 to save the files  releated to the images of pixels.

Step2 :

In step 2 server side we get all files successfully, and we are using a for loop to get individual files of type, size, name, Temporary file Location, extension of file from $_FILES global variable. Now we are send each file to CreateThumb() function to resize the images and store the images in folder with the help of bellow functions ,I explained in step 3 , step 4 ,step 5, step 6 .

Step3 :


imagecreatefromjpeg ( string $filename )

This function used to create an image from what we passed Parameter to this function. It accepts single parameter this Parameter stores the URL or file location to create an JPEG image.

Step4 :


imagecreatetruecolor ( int $width , int $height ) 

This function used to create an true color black image (transparency is black) with specific sizes

Step5 :

imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int$dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h)

This function  used to copy the imagecreatefromjpeg()(step 3) into imagecreatetruecolor() (step 4) and resize the image from original pixes to what  your selected pixels

Step6 :


imagejpeg ( resource $image [, string $filename [, int $quality ]] )

This function is used to save the file into folder.

Add bellow CSS code in HTML head


<style>
body {
 font-family: serif;
}
.jumbotron {
 margin-bottom: 0px
}
.pixels-1::before {
 content:&quot;width:200px&quot;;
 color:rgb(105, 37, 207);
 font-weight:bold;
}
.pixels-2::before {
 content:&quot;width:100px&quot;;
 color:rgb(105, 37, 207);;
 font-weight:bold;
}
.pixels-3::before {
 content:&quot;width: 50px&quot;;
 color:rgb(105, 37, 207);;
 font-weight:bold;
}
.original-image::before {
 content:&quot;Original Image&quot;;
 color:rgb(105, 37, 207);;
 font-weight:bold;
}
.img-thumbnail {
 display: block;
}
.error-msg {
 color:red ;
 font-weight:bold;
}
.fileUpload {
 position: relative;
 overflow: hidden;
 margin: 10px;
}
.fileUpload input.upload {
 position: absolute;
 top: 0;
 right: 0;
 margin: 0;
 padding: 0;
 font-size: 20px;
 cursor: pointer;
 opacity: 0;
 filter: alpha(opacity=0);
}

</style>

 

Add bellow code in HTML body


<div class="container">
 <div class="jumbotron">
 <h2>Ajax multiple image upload resize with jquery and php</h2>
 </div>
<div id="form1">
 <form action="" method="post" enctype="multipart/form-data" id="image-form">
 <div class="fileUpload btn btn-primary">
 <span>Choose files</span>
 <input type="file" class="upload" name="files[]" id="files" multiple />
 </div>
 <input type="submit" id="submit-btn" name="submit" class="btn btn-primary" />
 </form>
</div>

<div class="error-msg"></div>
<div id="img_preview"></div>
</div>

Add bellow code in JavaScript


<script src="jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="form.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function(){
 $("#files").on("change",function(e){ //"e" object is received by callback function when Change event handler triggered.
 var image = e.target.files; //e object have a target object and it have files property to store files
 $("#image-form").on("submit",function(e) { 
 e.preventDefault();
 for(i=0;i<image.length;i++) { 
 var currentImage = image[i], name = currentImage.name, size=currentImage.size, type=currentImage.type, 
 ext = name.split('.').pop().toLowerCase(), get_size = size/1024, fileExtensions = ["jpeg","jpg","png","gif"];
 
 if( $.inArray(ext, fileExtensions) == -1) {
 $(".error-msg").append("one of file your uploaded not supporting to upload</br>");
 $("#files").val("");
 $("#form1").hide();
 return false;
 } else { if(Math.round(get_size) > 1024) {
 $(".error-msg").append( name+" is more than 1 MB size <br/>"); 
 $("#files").val("");
 $("#form1").hide();
 return false;
 }
 }
 
} var form_data=new FormData($("form#image-form")[0]); //
 $.ajax({
 type:"POST",
 url:"http://localhost/ajax-multiple-images-resize/upload.php",
 data:form_data,
 async: false,
 success:function(data){
 $("#files").val("");
 $("#img_preview").html(data);
 $("#form1").hide();
 },
 cache: false,
 contentType: false,
 processData: false,
 });
 });
 
 });
});


</script>

Add bellow code in PHP


<?php
function createThumb($ext,$temporaryFile,$filePath,$fileName,$newwidth) {

 $imageSize = getimagesize($temporaryFile); // Get the size of an image.It rerurns an array.
 $width = $imageSize[0]; // Get width of image in Pixels
 $height = $imageSize[1]; // Get height of image in pixels
 
 if($ext=="jpg" || $ext=="jpeg" ) {
 $src = imagecreatefromjpeg($temporaryFile); //returns a new created image from file or URL
 } else if($ext=="png") {
 $src = imagecreatefrompng($temporaryFile);
 } else if($ext=="gif") {
 $src = imagecreatefromgif($temporaryFile);
 } 
 
 $newheight=($height/$width)*$newwidth; //Get the new height of image
 $temporaryBlackFile=imagecreatetruecolor($newwidth,$newheight); //returns a new true color black image with specified sizes
 imagecopyresampled($temporaryBlackFile,$src,0,0,0,0,$newwidth,$newheight,$width,$height); //Copy the new created image into black image and totally resize part of an image with resampling.
 
 $filename = $filePath.$newwidth.'/'.$fileName; 
 if($ext=="jpg" || $ext=="jpeg" ) {
 imagejpeg($temporaryBlackFile,$filename,100); //copy the image into folder
 } else if($ext=="png") {
 imagepng($temporaryBlackFile,$filename,100);
 } else {
 imagegif($temporaryBlackFile,$filename,100);
 }
 
 imagedestroy($temporaryBlackFile); //cancel the Temporary file location
 return $filename;
}

if(isset($_POST["submit"])){
 $count=count($_FILES['files']['name']);
 $filePath = "upload/";
 
 for($i=0;$i<$count;$i++ ) {
 
 $temporaryFile = $_FILES['files']['tmp_name'][$i]; //get the Temporary location of file
 $temporaryName = $_FILES['files']['name'][$i]; //get the name of file.
 $extensionFile = pathinfo($temporaryName, PATHINFO_EXTENSION);
 $fileName = date("Y-m-d-h-i-s").rand().".".$extensionFile;
 $widthOfImages = array(200,100,50); //You can change dimension here.
 $a=1;
 foreach($widthOfImages as $newwidth) {
 $filename=createThumb($extensionFile,$temporaryFile,$filePath,$fileName,$newwidth); //Create a Image Thumbnails
 echo "<span class='pixels-$a'><img src='".$filename."' class='img img-responsive img-thumbnail'/></span></br>";
 $a++;
 }
 move_uploaded_file($temporaryFile,$filePath.$fileName);//Move Original file from Temporary location to Original loca
 $files[$i] = $fileName ; 
 }
 foreach($files as $file){ ?>
 <span class="original-image"><img src="upload/<?php echo $file ?>" class="img-responsive img-thumbnail"/></span><br/> 

<?php } } ?>