crop images using jcrop plugin

crop images using jcrop plugin

crop images using jcrop plugin

For image based web application and websites, Image cropping is one of the important functionality.

There are many useful jquery plugins are available for image cropping. Jcrop is one of the best cross browser jQuery image crop plugin available in the web world

Jcrop provide simple functionalists to crop images
Let us check how we can crop images using jcrop plugin.

Here I’m giving a simple example to crop image using jcrop plugin.
By enabling most of the options and giving an option to crop image.
This is combining most of the options of jcrop and creating a working image crop functionality.

So let us create a php script for coping

    if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
	$targ_w = $targ_h = 150;
	$jpeg_quality = 90;

	$src = 'demos/sago.jpg';
	$img_r = imagecreatefromjpeg($src);
	$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

	imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
	$targ_w,$targ_h,$_POST['w'],$_POST['h']);

	header('Content-type: image/jpeg');
	imagejpeg($dst_r,null,$jpeg_quality);

	exit;
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
    <title>crop images using jcrop plugin</title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
    <script src="js/jquery.Jcrop.js" type="text/javascript"></script>
    <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
    <link rel="stylesheet" href="demos/demos.css" type="text/css" />
    <style type="text/css">
      .optdual { position: relative; }
      .optdual .offset { position: absolute; left: 18em; }
      .optlist label { width: 16em; display: block; }
      #dl_links { margin-top: .5em; }
    </style>
    <script type="text/javascript">

      jQuery(function($){

        // The variable jcrop_api will hold a reference to the
        // Jcrop API once Jcrop is instantiated.
        var jcrop_api;

        // In this example, since Jcrop may be attached or detached
        // at the whim of the user, I've wrapped the call into a function
        initJcrop();

        // The function is pretty simple
        function initJcrop()//{{{
        {
          // Hide any interface elements that require Jcrop
          // (This is for the local user interface portion.)
          $('.requiresjcrop').hide();

          // Invoke Jcrop in typical fashion
          $('#target').Jcrop({
            onRelease: releaseCheck
          },function(){

            jcrop_api = this;
            jcrop_api.animateTo([100,100,400,300]);

            // Setup and dipslay the interface for "enabled"
            $('#can_click,#can_move,#can_size').attr('checked','checked');
            $('#ar_lock,#size_lock,#bg_swap').attr('checked',false);
            $('.requiresjcrop').show();

          });

        };
        //}}}

        // Use the API to find cropping dimensions
        // Then generate a random selection
        // This function is used by setSelect and animateTo buttons
        // Mainly for demonstration purposes
        function getRandom() {
          var dim = jcrop_api.getBounds();
          return [
            Math.round(Math.random() * dim[0]),
            Math.round(Math.random() * dim[1]),
            Math.round(Math.random() * dim[0]),
            Math.round(Math.random() * dim[1])
          ];
        };

        function releaseCheck()
        {
          jcrop_api.setOptions({ allowSelect: true });
          $('#can_click').attr('checked',false);
        };

        // Attach interface buttons
        // This may appear to be a lot of code but it's simple stuff
        $('#setSelect').click(function(e) {
          // Sets a random selection
          jcrop_api.setSelect(getRandom());
        });
        $('#animateTo').click(function(e) {
          // Animates to a random selection
          jcrop_api.animateTo(getRandom());
        });
        $('#release').click(function(e) {
          // Release method clears the selection
          jcrop_api.release();
        });
        $('#disable').click(function(e) {
          // Disable Jcrop instance
          jcrop_api.disable();
          // Update the interface to reflect disabled state
          $('#enable').show();
          $('.requiresjcrop').hide();
        });
        $('#enable').click(function(e) {
          // Re-enable Jcrop instance
          jcrop_api.enable();
          // Update the interface to reflect enabled state
          $('#enable').hide();
          $('.requiresjcrop').show();
        });
        $('#rehook').click(function(e) {
          // This button is visible when Jcrop has been destroyed
          // It performs the re-attachment and updates the UI
          $('#rehook,#enable').hide();
          initJcrop();
          $('#unhook,.requiresjcrop').show();
          return false;
        });
        $('#unhook').click(function(e) {
          // Destroy Jcrop widget, restore original state
          jcrop_api.destroy();
          // Update the interface to reflect un-attached state
          $('#unhook,#enable,.requiresjcrop').hide();
          $('#rehook').show();
          return false;
        });

         $('#ar_lock').change(function(e) {
          jcrop_api.setOptions(this.checked?
            { aspectRatio: 4/3 }: { aspectRatio: 0 });
          jcrop_api.focus();
        });
        $('#size_lock').change(function(e) {
          jcrop_api.setOptions(this.checked? {
            minSize: [ 80, 80 ],
            maxSize: [ 350, 350 ]
          }: {
            minSize: [ 0, 0 ],
            maxSize: [ 0, 0 ]
          });
          jcrop_api.focus();
        });

      });

	  	$(function(){

				$('#target').Jcrop({
					aspectRatio: 1,
					onSelect: updateCoords
				});

			});

			function updateCoords(c)
			{
				$('#x').val(c.x);
				$('#y').val(c.y);
				$('#w').val(c.w);
				$('#h').val(c.h);
			};

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

    </script>

  </head>

  <body>
    <div id="outer">
    <div class="jcExample">
    <div class="article">

      <h1>crop images using jcrop plugin</h1>
      <img src="demos/sago.jpg" id="target" alt="Jcrop Image" />

      <div style="margin: .8em 0 .5em;">
        <span class="requiresjcrop">
          <button id="setSelect">setSelect</button>
          <button id="animateTo">animateTo</button>
          <button id="release">Release</button>
          <button id="disable">Disable</button>
        </span>
        <button id="enable" style="display:none;">Re-Enable</button>
        <button id="unhook">Destroy!</button>
        <button id="rehook" style="display:none;">Attach Jcrop</button>
      </div>

      <fieldset class="optdual requiresjcrop">
        <legend>Option Toggles</legend>
        <div class="optlist offset">
          <label><input type="checkbox" id="ar_lock" />Aspect ratio</label>
          <label><input type="checkbox" id="size_lock" />minSize/maxSize setting</label>
        </div>
        <div class="optlist">
          <label><input type="checkbox" id="can_click" />Allow new selections</label>
          <label><input type="checkbox" id="can_move" />Selection can be moved</label>
          <label><input type="checkbox" id="can_size" />Resizable selection</label>
        </div>
      </fieldset>

	  	<form action="index.php" 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" value="Crop Image" />
		</form>

    </div>
    </div>
    </div>
  </body>
</html>

So by using jcrop you can easily crop image.
Here I’m showing a simple way to crop using jcrop. You can try all advance way of coping

Jcrop Manual

Download                              Labs