AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home JavaScript jQuery & AJAX

Live Image Upload, Crop and Resize using jQuery and PHP

Live Image Upload, Crop and Resize using jQuery and PHP

Lakshika Mathur by Lakshika Mathur
December 24, 2019
Reading Time: 5 mins read
0
Live Image Upload

It is always an excellent idea for server space optimization to cropping images before upload. Firstly the crop feature helps to resize the image as per the required size before you upload it to the server. Secondly, you can decrease the web page size and load time by showing the image with the same display size. At last, there is a need to crop the image if you want to display the exact dimensions (width and height) on the web page. So, if your web application has image upload functionality, image crop and resize is beneficial.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

You can upload an image and make a thumbnail using PHP. But if you want live image upload and crop, then you need to use jQuery with the help of PHP. The jQuery will help you to select an area of the image, and PHP can help you to crop, resize, and upload the image on the server. So, there are many jQuery plugins available for cropping image, imgAreaSelect is one of them. The imgAreaSelect plugin will help you to select an area of an image and implement image resizing and cropping functionality. In this tutorial, we will explain to you, crop, and resize an image using jQuery and PHP.

Before you begin to implement live image upload and crop functionality, let’s take a look at the file structure.

image_upload_crop_jquery_php/
├── index.html
├── upload.php
├── js/
│   ├── jquery.imgareaselect.js
│   └── jquery.min.js
├── css/
│   └── imgareaselect.css
└── uploads/
    └── images/
        └── thumb/

JavaScript Code  

jQuery library:

Firstly, include the jQuery library file.

<!-- jQuery library -->
<script src="js/jquery.min.js"></script>

imgAreaSelect Plugin:

Use the imgAreaSelect plugin to implement image crop functionality. Also, include the imgAreaSelect plugin library file.

<!-- imgAreaSelect jQuery plugin -->
<link rel="stylesheet" href="css/imgareaselect.css" />
<script src="js/jquery.imgareaselect.js"></script>

The JavaScript code given below will create an instant image preview and permits the user to select an area of the image.

  • checkCoords() – Thie method checks whether the user selects a region of the image to crop.
  • updateCoords() – This method sets the coordinates, width, and height to the hidden input fields.
  • HTML5 FileReader You can use it to generate an instant preview of the selected image.
  • imgAreaSelect – This method is used to enable selection on an image, wrap it in a jQuery object, and call the imgAreaSelect() method.
// Check coordinates
function checkCoords(){
    if(parseInt($('#w').val())) return true;
    alert('Please select a crop region then press upload.');
    return false;
}

// Set image coordinates
function updateCoords(im,obj){
    var img = document.getElementById("imagePreview");
    var orgHeight = img.naturalHeight;
    var orgWidth = img.naturalWidth;
	
    var porcX = orgWidth/im.width;
    var porcY = orgHeight/im.height;
	
    $('input#x').val(Math.round(obj.x1 * porcX));
    $('input#y').val(Math.round(obj.y1 * porcY));
    $('input#w').val(Math.round(obj.width * porcX));
    $('input#h').val(Math.round(obj.height * porcY));
}

$(document).ready(function(){
    // Prepare instant image preview
    var p = $("#imagePreview");
    $("#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
    $('#imagePreview').imgAreaSelect({
        onSelectEnd: updateCoords
    });
});

HTML Code       

The following HTML makes an image upload form to select an image.

  • Firstly, the hidden input fields hold the coordinates info of the selected image.
  • Secondly, if the user selects an image, it will show the preview, and the user can choose an area on the image to crop.
  • At last, after selecting the image region, submit the form to the upload.php for server-side processing.
<form method="post" action="upload.php" enctype="multipart/form-data" onsubmit="return checkCoords();">
    <p>Image: <input name="image" id="fileInput" size="30" 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>
<p><img id="imagePreview" style="display:none;"/></p>

SEE ALSO: Upload Multiple Images without Page Refresh using jQuery Ajax and PHP

Image Upload and Crop (upload.php)   

It handles the image upload, crop, and resize functionality using PHP.

  • Validate the image type.
  • Upload image using move_uploaded_file() function in PHP.
  • Crop and resize image using PHP.
    • imagecreatetruecolor() – Makes a new true color image.
    • imagecreatefromgif() / imagecreatefromjpeg() / imagecreatefrompng() – Make a new image from file or URL.
    • imagecopyresampled() – Copy and resize part of an image.
    • imagegif() / imagejpeg() / imagepng() – Output image to file.
    • imagedestroy() – Delete sample image.
  • Display cropped image.
<?php
$error = '';

// If the 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($fileName, strrpos($fileName, ".") + 1);
    
    // Specify the images upload path
    $largeImageLoc = 'uploads/images/'.$fileName;
    $thumbImageLoc = 'uploads/images/thumb/'.$fileName;

    // Check and validate file extension
    if((!empty($_FILES["image"])) && ($_FILES["image"]["error"] == 0)){
        if($fileExt != "jpg" && $fileExt != "jpeg" && $fileExt != "png" && $fileExt != "gif"){
            $error = "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
        }
    }else{
        $error = "Select an image file to upload.";
    }
 
    // If everything is ok, try to upload file
    if(empty($error) && !empty($fileName)){
        if(move_uploaded_file($fileTmp, $largeImageLoc)){
            // File permission
            chmod($largeImageLoc, 0777);
            
            // Get dimensions of the original image
            list($width_org, $height_org) = getimagesize($largeImageLoc);
            
            // Get image coordinates
            $x = (int) $_POST['x'];
            $y = (int) $_POST['y'];
            $width = (int) $_POST['w'];
            $height = (int) $_POST['h'];

            // Define the size of the cropped image
            $width_new = $width;
            $height_new = $height;
            
            // Create new true color image
            $newImage = imagecreatetruecolor($width_new, $height_new);
            
            // Create new image from file
            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;
            }
            
            // Copy and resize part of the image
            imagecopyresampled($newImage, $source, 0, 0, $x, $y, $width_new, $height_new, $width, $height);
            
            // Output image to file
            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;
            }
            
            // Destroy image
            imagedestroy($newImage);

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

// Display error
echo $error;
?>

Conclusion

These Live Image Upload, Crop and Resize scripts are convenient to crop the image and resize it. Also, you can upload a picture and make a thumbnail with the help of PHP.

Also, read our previous blog- Multiple Image Upload with View, Edit and Delete in PHP 

Also, read our previous blog- Image Gallery CRUD with PHP and MySQL

Tags: jQuery and PHPLive Image Upload
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
Form Validation using jQuery Validation Plugin
jQuery & AJAX

Form Validation using jQuery Validation Plugin

January 2, 2020
34
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
Next Post
Convert Array to XML and XML to Array in PHP

Convert Array to XML and XML to Array in PHP

Build CRUD DataGrid

Build CRUD DataGrid with jQuery EasyUI using PHP and MySQL

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version