How to Upload, Crop and Resize Image Using jQuery and PHP

If you are running a website, you may want to crop the image in certain scenarios. Let’s say you want to allow the user to crop their profile image. To achieve it practically you need to perform the following steps:

  • Give a file input to browse the image.
  • Show the preview version of this image.
  • Allow users to choose the area of the image they wish to crop.
  • Take the coordinates of the chosen area and send it to the server side.
  • Crop the image using coordinates and store it on the server.

These steps involve both front-end and back-end work. We will manage it using jQuery and PHP. There are libraries available to achieve this operation.

  • imgAreaSelect : This jQuery plugin allows you to choose the portion of the image.
  • Intervention Image : It’s an open-source PHP library used for image manipulation.

With the help of these libraries, we study how to upload, crop, and resize the image. I mentioned the term resize because eventually, we are resizing the original image as per the coordinates provided.

While cropping the image, I’ll store both the original and cropped version of an image on the server. The users can change this behavior if they don’t need both versions.

Installation

Download the imgAreaSelect plugin from the linked page. For installation of the Intervention Image library, I recommend using Composer. Run the command below in the project root directory to install the library.

composer require intervention/image

When you are done make sure your directory structure looks like a screenshot below.

folder-structure

How to Use imgAreaSelect

In order to use imgAreaSelect, you are required to include its CSS and JS file along with the jQuery library.

<link rel="stylesheet" href="css/imgareaselect.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="js/jquery.imgareaselect.js"></script>

Next, we require a simple form where the user can browse the image, preview it, choose the portion, and submit it for server-side processing.

<form action="crop.php" method="post" enctype="multipart/form-data">
    Upload Image: <input type="file" name="image" id="image" />
    <input type="hidden" name="x1" value="" />
    <input type="hidden" name="y1" value="" />
    <input type="hidden" name="w" value="" />
    <input type="hidden" name="h" value="" /><br><br>
    <input type="submit" name="submit" value="Submit" />
</form>
 
<p><img id="previewimage" style="display:none;"/></p>

The above form will display the file input and submit button. I have taken hidden fields in the form to hold the coordinate values like the x-y axis, width, and height. These hidden field values will help crop the image through coordinates.

When the user browses an image, we will show the image so a user can select the area which they need to crop. The below code will display a preview version of the image and allows them to choose a portion of the image. The preview will display using the img tag having a previewimage id.

<script>
jQuery(function($) {
 
    var p = $("#previewimage");
    $("body").on("change", "#image", function(){
 
        var imageReader = new FileReader();
        imageReader.readAsDataURL(document.getElementById("image").files[0]);
     
        imageReader.onload = function (oFREvent) {
            p.attr('src', oFREvent.target.result).fadeIn();
        };
    });
 
    $('#previewimage').imgAreaSelect({
        onSelectEnd: function (img, selection) {
            $('input[name="x1"]').val(selection.x1);
            $('input[name="y1"]').val(selection.y1);
            $('input[name="w"]').val(selection.width);
            $('input[name="h"]').val(selection.height);            
        }
    });
});
</script>

Server-Side Upload, Crop, and Resize Image

Upon form submission, it redirects to the crop.php URL where we upload and crop the image using PHP script. In the crop.php file, we get the image and coordinates chosen by a user. The next work would be done by the Intervention Image library.

Let’s include the environment of the Intervention Image library.

<?php
require 'vendor/autoload.php';
 
use Intervention\Image\ImageManagerStatic as Image;

I am going to use a crop() method of a library to cut out a certain portion of the original image. Parameters for the crop() function are width, height, and x, y coordinates. You may read more about it in the documentation.

crop.php

<?php
require 'vendor/autoload.php';
 
use Intervention\Image\ImageManagerStatic as Image;
 
if(isset($_POST['submit'])) {
     
    if(isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
 
        if(!file_exists('images')) {
            mkdir('images', 0755);
        }
 
        $filename = $_FILES['image']['name'];
        $filepath = 'images/'. $filename;
        move_uploaded_file($_FILES['image']['tmp_name'], $filepath);
         
        if(!file_exists('images/crop')) {
            mkdir('images/crop', 0755);
        }
 
        // crop image
        $img = Image::make($filepath);
        $croppath = 'images/crop/'. $filename;
 
        $img->crop($_POST['w'], $_POST['h'], $_POST['x1'], $_POST['y1']);
        $img->save($croppath);
 
        echo "<img src='". $croppath ."' />";
    }
}

Here, I am creating images and crop directories programmatically if they do not exist. Now if you test the flow you will get the original and cropped version of the image stored under the images and crop directories respectively.

Set Maximum Width on Image

The user may want to define the maximum width to choose a certain position of an image. The imgAreaSelect plugin provides several options like aspectRatio, maxWidth, maxHeight, etc. to customize the final result of an image. As an example, a user can use the maxWidth option to set the maximum width while choosing an area of the image. In the below code, I set a maximum width as 1000px.

$('#previewimage').imgAreaSelect({
    maxWidth: '1000', // this value is in pixels
    onSelectEnd: function (img, selection) {
        $('input[name="x1"]').val(selection.x1);
        $('input[name="y1"]').val(selection.y1);
        $('input[name="w"]').val(selection.width);
        $('input[name="h"]').val(selection.height);            
    }
});

I hope you understand how to upload, crop, and resize the image using jQuery and PHP. This tutorial should help you to crop the image easily and it saves you time. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

7 thoughts on “How to Upload, Crop and Resize Image Using jQuery and PHP

  1. Nice plugin guys. I really like your work. Keep it up. Please could you help me how to use crop.php in ajax jquery. Thanks!

  2. Hi, I’m trying to get this going for my website https://peoplelikeus.world. I want to use it to crop user images to a standard square.
    Do you have a working demo somewhere? I can’t work out what’s meant to happen when I upload the file, whether it should show immediately when I ‘open’ it or whether I’m first supposed to upload it and then have it display in the preview.
    Cheers,
    Drew

Leave a Reply

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