Live Image Upload, Crop and Resize using jQuery and PHP


Cropping image before upload, always a great idea for server space optimization. Crop feature helps to resize the image as per the required size. You can also reduce the web page size and load time by showing the exact size image. If your web application has image upload functionality, image crop and resize are very useful.

You can easily upload image and create thumbnail using PHP. But if you want live image upload and crop, jQuery needs to be used. In this tutorial, we will show you how to upload, crop, and resize image using jQuery and PHP. There are many jQuery plugins available for cropping image, imgAreaSelect is one of them. The imgAreaSelect plugin helps to select an area of an image and implement image cropping and resizing functionality.

Before you get started to implement live image upload and crop functionality, take look the files structure.

image-upload-crop-jquery-php-files-structure-codexworld

imgAreaSelect Plugin & jQuery

The imgAreaSelect plugin and jQuery will be used to implement image crop functionality. So, at first, include the imgAreaSelect plugin and jQuery library.

<link rel="stylesheet" type="text/css" href="css/imgareaselect.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.imgareaselect.js"></script>

JavaScript Code

The following JavaScript code generates an instant image preview and allows the user to select an area of the image.

  • updateCoords() – This method set the coordinates, width, and height to the input fields.
  • checkCoords() – Thie method checks whether the user selects a region of the image to crop.
  • HTML5 FileReader is used to generate instant preview of the selected image.
  • imgAreaSelect – To enable selection on an image, wrap it in a jQuery object and call the imgAreaSelect() method.
<script>
//set image coordinates
function updateCoords(im,obj){
    $('#x').val(obj.x1);
    $('#y').val(obj.y1);
    $('#w').val(obj.width);
    $('#h').val(obj.height);
}

//check coordinates
function checkCoords(){
    if(parseInt($('#w').val())) return true;
    alert('Please select a crop region then press submit.');
    return false;
}

$(document).ready(function(){
    //prepare instant image preview
    var p = $("#filePreview");
    $("#fileInput").change(function(){
        //fadeOut or hide preview
        p.fadeOut();

        //prepare HTML5 FileReader
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("fileInput").files[0]);

        oFReader.onload = function (oFREvent) {
            p.attr('src', oFREvent.target.result).fadeIn();
        };
    });

    //implement imgAreaSelect plugin
    $('img#filePreview').imgAreaSelect({
        // set crop ratio (optional)
        //aspectRatio: '2:1',
        onSelectEnd: updateCoords
    });
});
</script>

HTML Code

The following HTML creates an image upload form to select an image. The hidden input fields hold the coordinates info of the selected image.

<form action="upload.php" enctype="multipart/form-data" method="post" onsubmit="return checkCoords();">
    <p>Image: <input name="image" id="fileInput" type="file" /></p>
    <input type="hidden" id="x" name="x" />
    <input type="hidden" id="y" name="y" />
    <input type="hidden" id="w" name="w" />
    <input type="hidden" id="h" name="h" />
    <input name="upload" type="submit" value="Upload" />
</form>

Once the user selects an image, the preview will be shown and the user can select an area on the image to crop.

<p><img id="filePreview" style="display:none;"/></p>

After selecting the image region, the form will be submitted to the upload.php for further processing.

Image Upload and Crop (upload.php)

The upload.php file handles the image upload and crop functionality using PHP.

  • Validate image type.
  • Upload image using move_uploaded_file() function in PHP.
    • Crop and resize image using PHP.
    • imagecreatetruecolor() – Create a new true color image.
    • imagecreatefromgif() / imagecreatefromjpeg() / imagecreatefrompng() – Create a new image from file or URL.
    • imagecopyresampled() – Copy and resize part of an image with resampling.
    • imagegif() / imagejpeg() / imagepng() – Output image to file.
  • Display cropped image.
<?php
//if upload form is submitted
if(isset($_POST["upload"])){
    
//get the file information
    
$fileName basename($_FILES["image"]["name"]);
    
$fileTmp $_FILES["image"]["tmp_name"];
    
$fileType $_FILES["image"]["type"];
    
$fileSize $_FILES["image"]["size"];
    
$fileExt substr($fileNamestrrpos($fileName".") + 1);
    
    
//specify image upload directory
    
$largeImageLoc 'uploads/images/'.$fileName;
    
$thumbImageLoc 'uploads/images/thumb/'.$fileName;
 
    
//check file extension
    
if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)){
        if(
$fileExt != "jpg" && $fileExt != "jpeg" && $fileExt != "png"){
            
$error "Sorry, only JPG, JPEG & PNG files are allowed.";
        }
    }else{
        
$error "Select a JPG, JPEG & PNG image to upload";
    }
    
    
//if everything is ok, try to upload file
    
if(strlen($error) == && !empty($fileName)){
        if(
move_uploaded_file($fileTmp$largeImageLoc)){
            
//file permission
            
chmod ($largeImageLoc0777);
            
            
//get dimensions of the original image
            
list($width_org$height_org) = getimagesize($largeImageLoc);
            
            
//get image coords
            
$x = (int) $_POST['x'];
            
$y = (int) $_POST['y'];
            
$width = (int) $_POST['w'];
            
$height = (int) $_POST['h'];

            
//define the final size of the cropped image
            
$width_new $width;
            
$height_new $height;
            
            
//crop and resize image
            
$newImage imagecreatetruecolor($width_new,$height_new);
            
            switch(
$fileType) {
                case 
"image/gif":
                    
$source imagecreatefromgif($largeImageLoc); 
                    break;
                case 
"image/pjpeg":
                case 
"image/jpeg":
                case 
"image/jpg":
                    
$source imagecreatefromjpeg($largeImageLoc); 
                    break;
                case 
"image/png":
                case 
"image/x-png":
                    
$source imagecreatefrompng($largeImageLoc); 
                    break;
            }
            
            
imagecopyresampled($newImage,$source,0,0,$x,$y,$width_new,$height_new,$width,$height);

            switch(
$fileType) {
                case 
"image/gif":
                    
imagegif($newImage,$thumbImageLoc); 
                    break;
                case 
"image/pjpeg":
                case 
"image/jpeg":
                case 
"image/jpg":
                    
imagejpeg($newImage,$thumbImageLoc,90); 
                    break;
                case 
"image/png":
                case 
"image/x-png":
                    
imagepng($newImage,$thumbImageLoc);  
                    break;
            }
            
imagedestroy($newImage);
            
            
//remove large image
            //unlink($imageUploadLoc);

            //display cropped image
            
echo 'CROP IMAGE:<br/><img src="'.$thumbImageLoc.'"/>';
        }else{
            
$error "Sorry, there was an error uploading your file.";
        }
    }else{
        
//display error
        
echo $error;
    }
}
?>

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

Leave a reply