How to Crop Image Using JavaScript and PHP

Image cropping is a usefull feature in web application that allows user to crop an image on a web page and save it for later use. This feature is commonly used in user’s preferences tool for creating a profile image. User uploads an image from his local hardrive and then directly crop his desired part for used as his profile image without using an image editing software.

Image Cropping

Image Cropping

Image cropping process can be separated into two separated process. The first process is for acquaring coordinates and dimensions of selected area of an image, which will be done in client side using JavaScript. The next is process for creating a new image based on coordinates and dimensions from previously cropping process using PHP on server side. In this tutorial, i’ll use JavaScript Image Cropper library by David Spurr and PHP GD image processing functions.

Client Side

Image Cropper is an excellent JavaScript library written by David Spurr that makes image cropping easier. It allows us to crop an image using an interface with the same features and styling as found in commercial image editing software. It is based on Prototype JavaScript Framework and Scriptaculous.

How to Setup

  1. Download the required library files
  2. - Prototype Javascript Framework

    - Scriptaculous (scriptaculous-js-1.8.3.zip)

    - Image Cropper (jsCropperUI-1.2.1.zip)

  3. Extract scriptaculous-js-1.8.3.zip and copy scriptaculous.js, builder.js, effect.js and dragdrop.js from the extracted files into your web application directory.
  4. Extract jsCropperUI-1.2.1.zip and copy cropper.js, marqueeHoriz.gif, marqueeVert.gif, cropper.css from the extracted files into your web application directory ( must reside in the same directory).
  5. Include Prototype.js, scriptaculous.js and cropper.js in the HEAD section of your HTML file.
    <script src="scripts/prototype.js" type="text/javascript"></script>
    <script src="scripts/scriptaculous.js?load=effects,builder,dragdrop" type="text/javascript"></script>
    <script src="scripts/cropper.js" type="text/javascript"></script>
    

Using Image Cropper Library

With Dynamic Crop Preview

<script type="text/javascript" charset="utf-8">
Event.observe (
	window,
	'load',
	function() {
		new Cropper.ImgWithPreview(
			't3soeta',
			{
				minWidth: 200,
				minHeight: 100,
                ratioDim: { x: 200, y: 100 },
				displayOnInit: true,
				onEndCrop: saveCoords,
                onloadCoords: { x1: 0, y1: 0, x2: 200, y2: 100 },
                previewWrap: 'preview'
			}
		)
	}
);

function saveCoords (coords, dimensions)
{
	$( 'x1' ).value = coords.x1;
	$( 'y1' ).value = coords.y1;
	$( 'width' ).value = dimensions.width;
	$( 'height' ).value = dimensions.height;
}
</script>

<form action="saveCrop.php" method="post">
<div style="width:750px">
    <div style="float:left">
        <img src="images/t3soeta.jpg" id="t3soeta" width="500" height="375" />
    </div>
    <div id="preview" style="float:right;"></div>
    <div style="clear:both"></div>
    <input type="hidden" name="x1" id="x1" value="">
    <input type="hidden" name="y1" id="y1" value="">
    <input type="hidden" name="width" id="width" value="">
    <input type="hidden" name="height" id="height" value="">
</div>
<input type="submit" name="Done" value=" Done ">
</form>

Line 06: Instantiate Image Cropper class.

Line 07: Image Id.

Line 09: minWidth, is the minimum width for selected area in pixels.

Line 10: minHeight, is the minimum height for selected area in pixels.

Line 11: ratioDim, is the pixel dimensions to apply as a restrictive ratio, with properties x & y.

Line 12: displayOnInit, whether display the selected area on initialisation. If set to true, minWidth and minHeight or ratioDim must be provided.

Line 13: onEndCrop, a callback function which will be called when user finished a crop movement. The function takes two arguments:

  • coords, is the coordinates of selected area with properties x1, y1, x2, y2.
  • dimensions , is the dimensions of selected area with properties width and height.

On example above (Line 21), coordinates and dimensions are stored in hidden elements and will be sent to server side script (saveCrop.php) using HTTP POST method for later processing .

Line 14: onloadCoords, is the coordinates of the selected area to display onload

Line 15: previewWrap, is the id of container for image crop preview.

Line 21: callback function, as set on onEndCrop option (Line 13).

Line 33: image to be cropped, it’s id must match the id set on Line 07.

Line 35: div container for image crop preview.

Line 37-40: Hidden elements to store coordinates and dimensions of selected area.

View live demo here

Without Dynamic Crop Preview

For using Image Cropper without dynamic preview, change the class from Cropper.ImgWithPreview to Cropper.Img and remove the previewWrap option.

Event.observe (
	window,
	'load',
	function() {
		new Cropper.Img (
			't3soeta',
			{
				minWidth: 200,
				minHeight: 100,
                ratioDim: { x: 200, y: 100 },
				displayOnInit: true,
				onEndCrop: saveCoords,
                onloadCoords: { x1: 0, y1: 0, x2: 200, y2: 100 },
			}
		)
	}
);

View live demo here

Server Side

On server side, image is processed using PHP GD image functions, which required GD library installed.

<?php
$x1      = $_POST['x1'];
$y1      = $_POST['y1'];
$width   = $_POST['width'];
$height  = $_POST['height'];

$srcImg  = imagecreatefromjpeg('images/t3soeta.jpg');
$newImg  = imagecreatetruecolor($width, $height);

imagecopyresampled($newImg, $srcImg, 0, 0, $x1, $y1, $width, $height, $width, $height);

imagejpeg($newImg, 'images/cropped_t3soeta.jpg');
?>

Line 02-05: get coordinates and dimensions sent from client.

Line 07: create source image

Line 08: create a new true color image for cropped image

Line 10: copy selected area from source image into new image using coordinates and dimensions sent from client.

Line 12: Output the new cropped image into a file.

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

  1. tirengarfio says

    Hi Lorenz,

    i haven’t seen anything about cropper.css

    Shouldn’t be included some where?

    Regards

    Javi

  2. Camilo Cifuentes says

    Hi Lorenz,,

    thanks you very much for the script. Is nice and is very easy to modify, in fact, I made it work for .png and .gif images too.

  3. says

    Finally! A simple and great tutorial. So much trash in the net that makes us waste countless time looking for what we need.

    This one did the trick! Thank you.

  4. Aunonimous says

    Hi lorenz,

    This s awesome. But is there a way to retain the image size after cropping insteat of having a standard size.

    Thankz in advance.

  5. Pravin Ahire says

    Hi Lorenz,

    It’s very very good tutorial and it works fine…..this is what I was looking.

    Thanks in advance.

Leave a Reply

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