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

If you are running a website, then you may want to crop the image in certain scenarios. Let’s say you want to allow the user to crop their profile images before upload. In this article, we study how to upload, crop, and resize the image using imgAreaSelect and PHP.

We can say that when we crop the image, we are actually resizing it adjusting with the provided coordinates of the cropped portion.

imgAreaSelect is a jQuery plugin which provides a feature to cropping the images. It is a lightweight plugin and easy to use.

To get started, you need to use imgAreaSelect plugin and Intervention Image library. Using imgAreaSelect we choose the image area which needs to crop and Internention Image library help us to store the original and copped version of a image on the server.

Having said that, let’s take a look at how to upload, crop, and resize the image using jQuery and PHP.

Installation

Download the imgAreaSelect plugin from the given link. For installation of Interventon Image, I recommend to use Composer. Run the command below in the project root directory to install the Intervention Image library.

composer require intervention/image

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

How to Use imgAreaSelect

In order to use imgAreaSelect, we first need to include their 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.5.1/jquery.min.js"></script>
<script src="js/jquery.imgareaselect.js"></script>

Next, we require a simple form where the user can browse the image 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 which will need to crop the image on the server-side. Basically, these hidden fields send coordinates of the image for cropping it.

When the user browses the image, we will show the image where a user can select the area which they need to crop. The below code allows the user to preview the image and choose an area of the image to crop.

<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 file where we upload and crop the image on the server-side. This file accepts file input and coordinates of the image for cropping.

First, 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 create the cropped version of the original image. Parameters for the crop() function are width, height, and coordinates of x-axis and y-axis. You may read more about it on their 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 ."' />";
    }
}

That’s it! Now if you test the flow you will get the original and cropped version of the images stored under the ‘images’ and ‘crop’ directories respectively.

Set Maximum Width on Image

Sometimes, the user may want to define maximum width for a cropped versions of an image. imgAreaSelect provides several options like aspectRatio, maxWidth, maxHeight, etc. to customize the final result of an image. A user can use the maxWidth option to set the maximum width for the image.

$('#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. I would like to know your thoughts in the comment section below.

Related Articles

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

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

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