Crop image using jquery and php

In this session i am going to show you how to crop any image using jquery jcrop library and PHP GD library. You might have seen this feature on popular social networking website, When ever you upload your profile picture application asked to crop image to fit on screen.

There is a plugin called jcrop in jquery i am going to use to select image co-ordinates and image height width x and y co-ordinates and send it to server, On server side i used php gd library to crop image as per given co-ordinates.
cropimg
Let’s start..

Here i am not going to show you how to upload images, I’ll show you the next step directly after uploading image, How to crop it. You can see these tutorial to uploading images.
1). How to upload images with progress bar using jquery and php.
2). How to upload multiple images with progress bar using jquery and php.
3). How to upload images with progress bar using jquery and nodejs.




Create index.html file and call uploaded image.

index.html

 <link rel="stylesheet" href="css/jquery.Jcrop.min.css" type="text/css" />
 <div style="float:left; width:60%">
   <img src="img.jpg" id="cropbox" class="img" />
   <br/>
    <input type='button' id="crop" value='CROP IMAGE' id="detect" style="height:60px;cursor: pointer; color:green; font-weight:bold;" ></button>
   </div>
  <div style="float:right; width:40%">
    <img src="#" id="croped" style="display:none;">
  </div>
</div>

After that add jcrop library Note: jcrop library dependent on jquery core library so don’t forget to add core library first.

<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>

Now add jquery snippet to make selection on image co-ordinates and send it to server.

<script type="text/javascript">
  $(function(){
    var cod;
    $('#cropbox').Jcrop({
      aspectRatio: 1,
      onSelect: function(c){
       cod = {x:c.x,y:c.y,w:c.w,h:c.h};     
      }
    });
 
    $("#crop").click(function(){
      if(typeof(cod) == 'undefined') {
        alert("Please select crop area on image.");
        return false;
      }
      var img = $("#cropbox").attr('src');
        $("#croped").show();
        $("#croped").attr('src','img.php?x='+cod.x+'&y='+cod.y+'&w='+cod.w+'&h='+cod.h+'&img='+img);
    });
  });
</script>




Finally create your new croped image using PHP GD library.

img.php

<?php
  $imgPath = $_GET['img'];
  $targ_w = $targ_h = 150;
  $jpeg_quality = 90;
 
  $img_r = imagecreatefromjpeg($imgPath);
  $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
 
  imagecopyresampled($dst_r,$img_r,0,0,$_GET['x'],$_GET['y'],
  $targ_w,$targ_h,$_GET['w'],$_GET['h']);
 
  header('Content-type: image/jpeg');
  imagejpeg($dst_r,null,$jpeg_quality);
 
exit;
 
?>

See live demo and download full source code.

DEMO

DOWNLOAD

If you like this post please don’t forget to subscribe my public notebook for more useful stuff