Tutorial: How to Implement Jcrop into an Application

Published October 10, 2009 13 Comments 0 Delicious Bookmarks

How to use Jcrop from within an Application - Tutorial

When creating the ‘image control panel’ for the latest version of GetSimple, I decided to integrate the wonderful Jcrop jQuery plugin into it. Amazingly, there are very few tutorials online that show the full extent of how to use Jcrop in real world situations. The only one I found that was of use was TalkInCode’s tutorial. I did start out using that example’s ImageManipulation class, but changed it slightly so that after submission, you are brought back to the original page instead of being shown the thumbnail.

Demo & Features

View the Demo or download the files.

Some of the more unique features of this demo are:

  • The aspectRatio changes to 1:1 when ctrl-Q or command-Q is pressed
  • The dimensions of the selected area are shown in an interesting way
  • Stats on the thumbnail and the current image are displayed

The Basic HTML

The demo/download has some extra code for displaying the image stats & linking of the css, js and class files.

<!-- image for Jcrop -->
<img src="<?php echo $src_folder . $src; ?>" id="cropbox" />

<!-- selection dimentions -->
<div id="handw" class="toggle" >Selection Dimentions<br /><span id="picw"></span> x <span id="pich"></span></div>

<!-- form that Jcrop fills in -->
<form id="jcropform" action="image.php?i=<?php echo $src; ?>" method="post" onsubmit="return checkCoords();">
  <input type="hidden" id="x" name="x" />
  <input type="hidden" id="y" name="y" />
  <input type="hidden" id="w" name="w" />
  <input type="hidden" id="h" name="h" />
  <input type="submit" class="submit" value="Create Thumbnail" />
    <span class="small" ><em>ctrl-Q</em> or <em>command-Q</em> for square</span>
</form>

The PHP

//the name of the passed image
//example would be:   http://myapplication.com/image.php?i=photo.jpg
$src = $_GET['i'];

//folder where the images are
$src_folder = 'images/';

//folder where the thumbnails will be saved to
//you may need to chmod 775 or 777 this folder
$thumb_folder = 'images/thumbnails/'; 

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

	require('inc/imagemanipulation.php');

	$objImage = new ImageManipulation($src_folder . $src);
	if ( $objImage->imageok ) {
		$objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']);
		$objImage->save($thumb_folder . 'thumbnail.' .$src);
	} else {
		echo 'Error!';
	}
}

The jQuery

function updateCoords(c) {
	$('#handw').show();
  $('#x').val(c.x);
  $('#y').val(c.y);
  $('#w').val(c.w);
  $('#h').val(c.h);
  $('#pich').html(c.h);
  $('#picw').html(c.w);
};

function checkCoords()
{
  if (parseInt($('#x').val())) return true;
  alert('Please select a crop region then press submit.');
  return false;
};

jQuery(document).ready(function() { 

	$(window).load(function(){
	var api = $.Jcrop('#cropbox',{
    onChange: updateCoords,
    onSelect: updateCoords,
    boxWidth: 500,
    boxHeight: 500
  });
  var isCtrl = false;
	$(document).keyup(function (e) {
		api.setOptions({ aspectRatio: 0 });
		api.focus();
		if(e.which == 17) isCtrl=false;
	}).keydown(function (e) {
		if(e.which == 17) isCtrl=true;
		if(e.which == 81 && isCtrl == true) {
			api.setOptions({ aspectRatio: 1 });
			api.focus();
		}
	});
});

});

This entry was posted under jQuery, Tutorials and has an RSS feed
13 Comments | Save to Del.ico.us |  

13 Comments

  1. October 15th, 2009 @ 6:36 am

    [...] week I showed how to implement Jcrop into an application. In this tutorial – which also pulls from my experiences developing GetSimple – I [...]

  2. October 26th, 2009 @ 11:11 pm

    Zilus said:

    Awsome!! just what I was looking for.

    I have only one problem… a have an image lets say 300×100 px, is there any way to use something like “Ratio” to keep proportions? For ex, if a user uploads a 1280x800px image, I’d like them to be able of crop and mantain the balance.

    Thanks!

  3. October 27th, 2009 @ 4:21 pm

    That would be a very useful feature… one that I would want too… let me look into it.

  4. Chris K said:

    Hi Chris,

    this is really great – the only thing I would REALLY need, that’s not in there YET is the “Ratio” feature that already has been asked for – any idea, how this could be done?

  5. March 29th, 2010 @ 10:38 am

    Greg said:

    I’m trying do download your files using link download the files but nothing heppend.
    Can you please send me files on my email account.
    Beautyfulll job

  6. August 27th, 2010 @ 6:14 am

    DBC said:

    Really handy piece of code bud and thank you for putting this online for all.

    Sadly I am having major troubles getting the image to be saved and cannot understand how to get it working. Was wondering if you could expand the tutorial text to explain each section in greater detail? :D

    Keep up the great work.

  7. Christo said:

    Ratio? There is an optional parameter for that: “aspectRatio”
    Just read the documentation from top to bottom!
    It only takes 2 minutes for craps sake!

    http://deepliquid.com/content/Jcrop_Manual.html

  8. October 29th, 2010 @ 9:11 am

    toshiro said:

    Thank’s for the Demo. But what about x-Coord = 0 ? There always comes up the alert “Please select a crop region then press submit.”
    I changed the function as follows:

    function checkCoords()
    {
    // if (parseInt($('#x').val())) return true;
    if (parseInt($('#x').val()) >= 0) return true;
    alert('Please select a crop region then press submit.');
    return false;
    };

    Now it works.

  9. Cyrus said:

    tnx for this tutorial, but I have one issue, How can I set the maximum width of thumbnail to 190px when the image is save, please help me, send me the code I really need this. Thankyou everyone

  10. Cyrus said:

    Sir Please Help me.

  11. adding aspectRatio: 1 to the jCrop object will allow you to crop only a box

  12. March 21st, 2011 @ 2:56 pm

    fadi said:

    thank u for this nice tutorial, however when i try to crop gif or png images i get a black thumbnail?? any ideas how can i fix this?
    thanks for the help

  13. April 30th, 2011 @ 7:53 am

    sahib said:

    hey guys please help me out i just download the script and jst tried it but m geting this error can anyone tell me how to slove this….???

    Warning: getimagesize(images/) [function.getimagesize]: failed to open stream: No such file or directory in C:\wamp\www\jcrop-demo\image.php on line 57

Leave your Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get your own Gravatar