Cropping images in runtime using Jcrop (jQuery)

Image Tutorials

Today we use jcrop api. During browsing the Internet I noticed one new good plugin which we can use to work with images. This is JCrop plugin, it can help us to perform different effect with images (as example highlight some objects using animation or zooming images. But main purpose is cropping.

Here are samples and downloadable package:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Ok, download the example files and lets start coding !


Step 1. HTML

As usual, we start with the HTML.

This is our main page code with 3 samples.

templates/jcrop_main.html

01 <script src="js/jquery.min.js"></script>
02 <script src="js/jquery.ui.widget.js"></script>
03 <script src="js/jquery.ui.accordion.js"></script>
04 <script src="js/jquery.Jcrop.min.js"></script>
05 <script src="js/jcrop_main.js"></script>
06 <link rel="stylesheet" href="templates/css/jquery.ui.theme.css" type="text/css" />
07 <link rel="stylesheet" href="templates/css/jquery.ui.accordion.css" type="text/css" />
08 <link rel="stylesheet" href="templates/css/jquery.Jcrop.css" type="text/css" />
09 <link rel="stylesheet" href="templates/css/jcrop_main.css" type="text/css" />
10 <div class="jcrop_example">
11     <div id="accordion" class="accordion">
12         <h3><a href="#">Jcrop - Crop Behavior</a></h3>
13         <div class="sample_1">
14             <div style="margin-bottom:10px;">
15                 <h4>Preview pane:</h4>
16                 <div style="overflow: hidden; width: 200px; height: 200px;">
17                     <img id="preview" src="files/image.jpg"/>
18                 </div>
19             </div>
20             <img src="files/image.jpg" id="cropbox1" />
21             <form action="index.php" method="post" onsubmit="return checkCoords();">
22                 <div style="margin:5px;">
23                     <label>X1 <input type="text" name="x" id="x" size="4"/></label>
24                     <label>Y1 <input type="text" name="y" id="y" size="4"/></label>
25                     <label>X2 <input type="text" name="x2" id="x2" size="4"/></label>
26                     <label>Y2 <input type="text" name="y2" id="y2" size="4"/></label>
27                     <label>W <input type="text" name="w" id="w" size="4"/></label>
28                     <label>H <input type="text" name="h" id="h" size="4"/></label>
29                 </div>
30                 <div style="margin:5px;">
31                     <input type="submit" value="Crop Image" />
32                 </div>
33             </form>
34             <p>
35                 <b>An example of crop script.</b> I decided to show form with values (you can keep it invisible if you want).
36                 Current sample ties several form values together with a event handler.
37                 Form values are updated as the selection is changed.
38                 Also current sample have preview area. So we will see our crop result.
39                 Aspect ratio disabled.
40                 If you press the <i>Crop Image</i> button, the form will be submitted and a 200x200 thumbnail will be dumped to the browser. Try it!
41             </p>
42         </div>
43         <h3><a href="#">Jcrop - Animations</a></h3>
44         <div class="sample_2">
45             <img src="files/image.jpg" id="cropbox2" />
46             <div style="margin: 20px 0;">
47                 <button id="anim1">Position 1</button>
48                 <button id="anim2">Position 2</button>
49                 <button id="anim3">Position 3</button>
50                 <button id="anim4">Position 4</button>
51                 <button id="anim5">Position 5</button>
52             </div>
53             <p>
54                 <b>Animating Selections.</b> We can use Jcrop API to set selections using animation (or immediately) to them. Here are several buttons are set to control the selection. User interactivity is still available. Try it!
55             </p>
56         </div>
57         <h3><a href="#">Jcrop - Custom styling</a></h3>
58         <div class="sample_3">
59             <img src="files/image.jpg" id="cropbox3" />
60             <p>
61                 <b>So maybe you like the color blue.</b>
62                 This demo shows how we can styling our Jcrop sample. This is easy - we will use addClass param to override styles. Also possible to set opacity using bgOpacity param (at current sample bgOpacity = 0.5). Also I used minSize param to determinate min size of selector (value = 50).
63             </p>
64         </div>
65     </div>
66 </div>

Step 2. CSS

Here are used CSS styles.

templates/css/jcrop_main.css

1 body{background:#eee;font-family:VerdanaHelveticaArialsans-serif;margin:0;padding:0}
2 .jcrop_example{background:#FFF;width:865px;font-size:80%;border:1px #000 solid;margin:3.5em 10% 2em;padding:1em 2em 2em}
3 .jcrop_example p{font-size:90%}
4 .accordion h3{margin:0}
5 .accordion form{border:1px solid;background:#E6E6E6;border-color:#C3C3C3 #8B8B8B #8B8B8B #C3C3C3;margin:.5em 0;padding:.5em}
6 .accordion form label{margin-right:1em;font-weight:700;color:#900;font-size:10px}
7 .jcrop_custom .jcrop-vline,.jcrop_custom .jcrop-hline{background:#FF0}
8 .jcrop_custom .jcrop-handle{background-color:#FF4B4B;-moz-border-radius:5px;-webkit-border-radius:5px;border-color:#FFF}

templates/css/jquery.Jcrop.css, templates/css/jquery.ui.accordion.css and templates/css/jquery.ui.theme.css

This is common files – styles of jquery elements. No need to give full code of that file here. It always available as a download package

Step 3. JS

Here are necessary JS files to our project.

js/jcrop_main.js

01 $(function(){
02     // for sample 1
03     $('#cropbox1').Jcrop({ // we linking Jcrop to our image with id=cropbox1
04         aspectRatio: 0,
05         onChange: updateCoords,
06         onSelect: updateCoords
07     });
08     // for sample 2
09     var api = $.Jcrop('#cropbox2',{ // we linking Jcrop to our image with id=cropbox1
10         setSelect: [ 100, 100, 200, 200 ]
11     });
12     var i, ac;
13     // A handler to kill the action
14     function nothing(e) {
15         e.stopPropagation();
16         e.preventDefault();
17         return false;
18     };
19     // Returns event handler for animation callback
20     function anim_handler(ac) {
21         return function(e) {
22             api.animateTo(ac);
23             return nothing(e);
24         };
25     };
26     // Setup sample coordinates for animation
27     var ac = {
28         anim1: [0,0,40,600],
29         anim2: [115,100,210,215],
30         anim3: [80,10,760,585],
31         anim4: [105,215,665,575],
32         anim5: [495,150,570,235]
33     };
34     // Attach respective event handlers
35     for(i in ac) jQuery('#'+i).click(anim_handler(ac[i]));
36     // for sample 3
37     $('#cropbox3').Jcrop({ // we linking Jcrop to our image with id=cropbox3
38         setSelect: [ 20, 130, 480, 230 ],
39         addClass: 'jcrop_custom',
40         bgColor: 'blue',
41         bgOpacity: .5,
42         sideHandles: false,
43         minSize: [ 50, 50 ]
44     });
45 });
46 function updateCoords(c) {
47     $('#x').val(c.x);
48     $('#y').val(c.y);
49     $('#w').val(c.w);
50     $('#h').val(c.h);
51     $('#x2').val(c.x2);
52     $('#y2').val(c.y2);
53     var rx = 200 / c.w; // 200 - preview box size
54     var ry = 200 / c.h;
55     $('#preview').css({
56         width: Math.round(rx * 800) + 'px',
57         height: Math.round(ry * 600) + 'px',
58         marginLeft: '-' + Math.round(rx * c.x) + 'px',
59         marginTop: '-' + Math.round(ry * c.y) + 'px'
60     });
61 };
62 jQuery(window).load(function(){
63     $("#accordion").accordion({autoHeight: false,navigation: true});
64 });
65 function checkCoords() {
66     if (parseInt($('#w').val())) return true;
67     alert('Please select a crop region then press submit.');
68     return false;
69 };

js/jquery.Jcrop.min.js, js/jquery.min.js, js/jquery.ui.accordion.js and js/jquery.ui.widget.js

This is common files – jQuery library with addon. No need to give full code of that file here. It always available as a download package

Step 4. PHP

Ok, here are all used PHP file:

index.php

01 <?php
02 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
03     $targ_w $targ_h = 200;
04     $jpeg_quality = 90;
05     $src 'files/image.jpg';
06     $img_r = imagecreatefromjpeg($src);
07     $dst_r = ImageCreateTrueColor( $targ_w$targ_h );
08     imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
09     $targ_w,$targ_h,$_POST['w'],$_POST['h']);
10     header('Content-type: image/jpeg');
11     imagejpeg($dst_r,null,$jpeg_quality);
12     exit;
13 }
14 require_once('templates/jcrop_main.html');
15 ?>

Step 5. Images

Also we need source image for our project:

    source image

Live Demo

Conclusion

Today we discussed about new interesting jquery plugin – Jcrop. Sure, that you will be happy to play with it. You can use this material to create your own scripts for your startups. Good luck!

Rate article