How to crop an image using PHP and JQuery

Introduction

The most common requirement over the modern web applications is upload image, crop as required or resize it, whether for profile picture use or any other use in photo galleries (small and bigger image) or as thumbnails. This post is going to be very interesting for the beginners who haven’t played with images for web applications and others can use this as a reference for the awesome web applications. We will cover all the basic requirement and we have also provided the source code for direct view of the output which you can use in every day situations. A small definition of cropping from Wikipedia:

Cropping refers to the removal of the outer parts of an image to improve framing, accentuate subject matter or change aspect ratio.

The Concept

Before we begin, I will briefly discuss the concept behind cropping an Image.

We will use a combination of Jquery and PHP to achieve our goal. More specifically we will utilize the imgAreaSelect jQuery plugin. We will also utilize Image functions specific to PHP.

Here is what we will be doing

  1.  Allow a user to make a selection by dragging over the Image. We also have a Preview Panel which lets user view the selection in real -time
  2. Hold the Coordinates of the selection in hidden Form Fields. We will utilize the onSelectEnd callback function. The onSelectEnd callback is fired as soon as a user finishes making the selection.
  3. Post selection coordinates to the crop.php file. The crop.php file will be responsible for final cropping of the image. We will utilize imagecreatetruecolor, imagecreatefromjpeg , imagecopyresampled and imagejpeg functions to actually crop the image
  4. Finally we will display the cropped image.

Note: We assume that you have basic PHP programming knowledge, and your server is up and running. We are also assuming that you have knowledge of how to upload image using PHP.

 

View Demo

Getting Started

Since, selecting an area of image cropping is a client-side functionality, and there is an jQuery plugin available to achieve the following task. So we will not re-invent the wheel. There are multiple plugins available, but here we are using imgAreaSelect jQuery plugin. Please follow the steps:

  1. Visit the imgAreaSelect website.
  2. Click on download button (right panel of website).
  3. Once you finish downloading it, extract the zip file.
  4. Add css and javascript file in your working directory.
  5. Add this in your HTML’s head section. Here you also need to include jquery library.
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />  
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" > </script>
<script type="text/javascript" src="js/jquery.imgareaselect.pack.js" > </script>

Create a file index.php and copy/ paste the following code:

<!doctype html>
<html lang="en">
<head>
    <title> How to crop image using PHP and JQuery </title>
    <meta charset="utf-8" >
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />  
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" > </script>
    <script type="text/javascript" src="js/jquery.imgareaselect.pack.js" > </script>
</head>
<body>
<div class="container" >
    <h3> Drag on image and select an area to crop </h3>
    <p>
        <img id="photo" src="nature.jpg" alt="Nature" title="Nature" />
    </p>
   <form action="crop.php" method="post" >
       <input type="hidden" name="x1" value="" />
       <input type="hidden" name="y1" value="" />
       <input type="hidden" name="x2" value="" />
       <input type="hidden" name="y2" value="" />
       <input type="hidden" name="width" value="" />
       <input type="hidden" name="height" value="" />
       <input type="submit" value="Crop" />
   </form>
</div>
<script>
    // This method is used to preview the selected area of main image
    function preview( img, selected ) {
        var scaleX = 200 / (selected.width || 1);
        var scaleY = 200 / (selected.height || 1);
        jQuery('#photo + div > img').css( {
            width: Math.round(scaleX * 400) + 'px',
            height: Math.round(scaleY * 400) + 'px',
            marginLeft: '-' + Math.round(scaleX * selected.x1) + 'px',
            marginTop: '-' + Math.round(scaleY * selected.y1) + 'px'
        });
    }

    // On document ready, we are placing an default image of image preview
    jQuery(document).ready(function () {
        jQuery('<div><img src="nature.jpg" style="position: relative;" /><div>').css( {
            float: 'left',
            position: 'relative',
            overflow: 'hidden',
            width: '200px',
            height: '200px',
            marginRight: '20px'
        }) .insertAfter(jQuery('#photo'));

    // On Initialization and select we are calling preview method
    // which displays selected image in parallel
    jQuery('#photo').imgAreaSelect( {
        aspectRatio: '1:1',
        handles: true,
        persistent: true,
        x1: 100, y1: 100, x2: 300, y2: 300,
        onInit: preview,
        onSelectChange: preview,
        onSelectEnd: function ( image, selected) {
            jQuery('input[name=x1]').val(selected.x1);
            jQuery('input[name=y1]').val(selected.y1);
            jQuery('input[name=x2]').val(selected.x2);
            jQuery('input[name=y2]').val(selected.y2);
            jQuery('input[name=width]').val(selected.width);
            jQuery('input[name=height]').val(selected.height);
        }
    });
});
</script>
</body>
</html>

Create a folder ‘css’ for all styles and then create a file style.css, copy/ paste the following code:

* {
    margin: 0 auto; 
    padding: 0;
}
body {
    background-color: #F2F2F2;
}
.container {
    margin: 0 auto;
    width: 920px;
    padding: 50px 20px;
    background-color: #fff;
}
h3 {
    text-align: center;
}
p {
    margin: 20px;
}
img {
    width: 400px;
    height: 400px;
}

This is how our first page would look like:

Crop ImageFigure1: Drag on right side image and select an area to crop

After clicking crop button, the hidden form parameters are sent to the crop.php page, where we have written the code for cropping an image and save the new image to the disk or directory. Before we create our main crop page, we need to understand few basic terms and syntax. The following are the PHP inbuilt functions:

  • imagecreatetruecolor – This method returns an image identifier representing a black image of the specified size. Create a new true color image(1) Syntax:
     imagecreatetruecolor ( int $width , int $height )
  • imagecreatefromjpeg – This method returns an image identifier representing the image obtained from the given filename. Create a new image from URL or file. (2) Syntax:
     imagecreatefromjpeg ( string $filename )
  • imagecopyresampled – This method copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. Copy and resize part of an image with resampling. (3) Syntax:
     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 )
  • imagejpeg – This method created a JPEG file from the given image. Output image to browser or file. (4) Syntax:
     imagejpeg ( resource $image [, string $filename [, int $quality ]] )

Create a file crop.php and copy/ paste the following code:

<?php
// Original image
$original_image = 'nature.jpg';
$new_image = 'nature1.jpg';
$image_quality = '95';

// Get dimensions of the original image
list( $current_width, $current_height ) = getimagesize( $original_image );

// Get coordinates x and y on the original image from where we
// will start cropping the image, the data is taken from the hidden fields of form.
$x1 = $_POST['x1'];
$y1 = $_POST['y1'];
$x2 = $_POST['x2'];
$y2 = $_POST['y2'];
$width = $_POST['width'];
$height = $_POST['height'];     
// print_r( $_POST ); die;

// Define the final size of the image here ( cropped image )
$crop_width = 200;
$crop_height = 200;
// Create our small image
$new = imagecreatetruecolor( $crop_width, $crop_height );
// Create original image
$current_image = imagecreatefromjpeg( $original_image );
// resampling ( actual cropping )
imagecopyresampled( $new, $current_image, 0, 0, $x1, $y1, $crop_width, $crop_height, $width, $height );
// this method is used to create our new image
imagejpeg( $new, $new_image, $image_quality );
?>

// HTML MARKUP
<!doctype html>
<html lang="en">
<head>
<title> How to crop image using PHP and JQuery </title>
<meta charset="utf-8" >
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container" >
    <h3> Cropped Image </h3>
    <p>
        <img id="photo" src="nature1.jpg" alt="Cropped Image" title="Cropped Image" style="width: 200px; height: 200px" />
    </p>
</div>
</body>
</html>

This is how our cropped image page would look like:

Cropped ImageFigure 2: Here we are displaying the cropped image from disk

Conclusion

Here we have created a very basic cropping tool. Obviously, there is a lot more to do. You can learn more while playing with the code and using your creativity. You can also crop images with different sizes as per requirements.

Reference

(1): http://php.net/manual/en/function.imagecreatetruecolor.php

(2): http://php.net/manual/en/function.imagecreatefromjpeg.php

(3): http://php.net/manual/en/function.imagecopyresampled.php

(4): http://php.net/manual/en/function.imagejpeg.php

 

Be creative and show us what else we can do after this. Please let us know, if you have any query related to cropping an image.

About Mohit Bhansali

A hyperactive mind with a passion for getting acquainted with the latest technology.

Comments

  1. Very good tutorial very helpful thanks for this tutorial i also learn from another tutorial a lot for image upload and cropping have a look here http://talkerscode.com/webtricks/resize-and-crop-image-using-php-and-jquery.php

Speak Your Mind

*