• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • About
  • Projects
    • GStaticMap WP Plugin
  • Contact
  • Privacy Policy

Lorenz Blog

All About Web & Mobile Application Development

  • Featured Articles
  • Gadgets
    • Android
    • Blackberry
  • Programming
    • Android
    • PHP
    • Java Script
    • MySQL
    • Postgresql
    • Flex
    • Web
  • Software
    • Mac OS
    • Windows
    • Linux
  • Web
You are Here » Home >> Information Technology >> Programming >> Java Script >> How to Crop Image Using JavaScript and PHP

How to Crop Image Using JavaScript and PHP

December 30, 2009 by Lorensius Londa 25 Comments

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.

Download Example Source Code
Facebooktwitterredditpinterestlinkedinmailby feather

Related posts:

  1. How to Create Scrollable Image Slider Using JavaScript
  2. How to Create Image Overlay Using Javascript
  3. How to Create Flash Like Image Slideshow with JavaScript
  4. How to Select and Crop Image on Android

Filed Under: Featured Articles, Information Technology, Java Script, PHP, Programming Tagged With: image crop, image crop guide, image crop howto, image crop javascript, image crop php, image crop tutorial, image cropping, javascript, jquery, PHP, php GD, prototype

About Lorensius Londa

Passionate web and mobile application developer. Co-founder of TRUSTUDIO, loves programming, Android, aviation, travelling, photography, coffee and gym mania.

Reader Interactions

Comments

  1. tirengarfio says

    January 7, 2010 at 3:27 am

    Hi Lorenz,

    i haven’t seen anything about cropper.css

    Shouldn’t be included some where?

    Regards

    Javi

    Reply
    • lorenz says

      January 8, 2010 at 9:03 am

      Hi Javi, thanx for the correction, the cropper.css should copied into directory where cropper.js resides. I’ve updated my post regarding it. 🙂

      Reply
      • sami says

        December 3, 2010 at 7:57 pm

        hello lorenz, Thanks ..

        Reply
      • Raji says

        July 2, 2012 at 1:42 pm

        how to import cropper.css from some other folder to cropper.js

        Reply
  2. ABel says

    February 11, 2010 at 4:08 am

    Thanks you, good tutorial.

    Reply
  3. nick says

    February 12, 2010 at 5:44 am

    This is the best! Thanks man.

    Reply
  4. Dorina says

    April 15, 2010 at 3:48 pm

    If i want to implement it in server side with image preview what should i do?

    Reply
  5. Camilo Cifuentes says

    May 20, 2010 at 8:29 pm

    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.

    Reply
    • lorenz says

      May 20, 2010 at 9:40 pm

      Hi Camilo, you’re welcome….:-)

      Reply
  6. AXL7 says

    July 18, 2010 at 7:30 am

    I don’t like this cropper. I LOVE it !!!

    Reply
  7. Miguel says

    July 19, 2010 at 2:13 am

    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.

    Reply
  8. james says

    October 6, 2010 at 1:49 am

    hi guys
    how would one implement this using dynamic images?

    Reply
  9. james says

    October 6, 2010 at 1:52 am

    hi guys
    How would one implement this with a dynamic image

    Reply
  10. ghd straightener says

    October 22, 2010 at 4:40 pm

    That’s a pretty nifty tool, thanks for the heads up I could use some more images for my site.

    Reply
  11. Kerem says

    October 24, 2010 at 1:19 am

    Great tutotial. i love it. But, its not work on I.E.

    Reply
  12. Aunonimous says

    December 4, 2010 at 1:51 pm

    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.

    Reply
  13. mosted says

    April 22, 2011 at 8:34 pm

    Why it doesn’t work on internet explorer. ?

    Reply
  14. Pravin Ahire says

    June 22, 2011 at 8:28 pm

    Hi Lorenz,

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

    Thanks in advance.

    Reply
  15. flukkytom says

    August 17, 2011 at 7:09 am

    Nice one.
    Thanks

    Reply
  16. veena says

    September 1, 2011 at 1:25 pm

    not working in IE why???????

    Reply
  17. Saurav says

    November 2, 2011 at 5:42 pm

    Where do we keep the marqueeHoriz.gif and marqueeVert.gif files?? …I kept them at the

    Reply
    • Saurav says

      November 2, 2011 at 5:45 pm

      same folder where I kept cropper.css and still I gave full adderss in url() of css page…still doesn’t work 🙁

      Reply
  18. janpasha says

    November 15, 2012 at 8:16 pm

    After server side saving corp image.
    Mouse event not stooping.
    Please tell me how to stop Event mouse click after save image

    Reply

Leave a Reply Cancel reply

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

Primary Sidebar

About Me

A husband, father of two, passionate software developer, diy lover and home baker who loves to learn new things. Read More…

  • Facebook
  • GitHub
  • Google+
  • Instagram
  • Twitter
  • YouTube

Featured Articles

How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Blue Bamboo P25 Printer Android Demo Application With Source Code

Simple JSON RPC Client for Android

How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP

Footer

Recent Comments

  • Aditya Dabas on About
  • Ayten Göksenin Barutçu on How to Make Android Map Scrollable Inside a ScrollView Layout
  • mang jojot on About
  • Hussain on How to Programmatically Scan or Discover Android Bluetooth Devices

Recent Posts

  • How to Fix Blank Screen on WordPress Add/Edit Post Page
  • How to Programmatically Restart the ESP32 Board
  • How to Get Hardware Info of ESP32
  • How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Latest Tweets

To protect our users from spam and other malicious activity, this account is temporarily locked. Please log in to https://twitter.com to unlock your account.

Copyright © 2023 · Magazine Pro on Genesis Framework · WordPress · Log in