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.
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.


 <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" />
    <input type='button' id="crop" value='CROP IMAGE' id="detect" style="height:60px;cursor: pointer; color:green; font-weight:bold;" ></button>
  <div style="float:right; width:40%">
    <img src="#" id="croped" style="display:none;">

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">
    var cod;
      aspectRatio: 1,
      onSelect: function(c){
       cod = {x:c.x,y:c.y,w:c.w,h:c.h};     
      if(typeof(cod) == 'undefined') {
        alert("Please select crop area on image.");
        return false;
      var img = $("#cropbox").attr('src');

Finally create your new croped image using PHP GD library.


  $imgPath = $_GET['img'];
  $targ_w = $targ_h = 150;
  $jpeg_quality = 90;
  $img_r = imagecreatefromjpeg($imgPath);
  $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
  header('Content-type: image/jpeg');

See live demo and download full source code.



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