Cropping images in runtime using Jcrop (jQuery)

Cropping images in runtime using Jcrop (jQuery)

33 114200

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

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

<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.ui.accordion.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<script src="js/jcrop_main.js"></script>
<link rel="stylesheet" href="templates/css/jquery.ui.theme.css" type="text/css" />
<link rel="stylesheet" href="templates/css/jquery.ui.accordion.css" type="text/css" />
<link rel="stylesheet" href="templates/css/jquery.Jcrop.css" type="text/css" />
<link rel="stylesheet" href="templates/css/jcrop_main.css" type="text/css" />
<div class="jcrop_example">
<div id="accordion" class="accordion">
<h3><a href="#">Jcrop - Crop Behavior</a></h3>
<div class="sample_1">
<div style="margin-bottom:10px;">
<h4>Preview pane:</h4>
<div style="overflow: hidden; width: 200px; height: 200px;">
<img id="preview" src="files/image.jpg"/>
</div>
</div>
<img src="files/image.jpg" id="cropbox1" />
<form action="index.php" method="post" onsubmit="return checkCoords();">
<div style="margin:5px;">
<label>X1 <input type="text" name="x" id="x" size="4"/></label>
<label>Y1 <input type="text" name="y" id="y" size="4"/></label>
<label>X2 <input type="text" name="x2" id="x2" size="4"/></label>
<label>Y2 <input type="text" name="y2" id="y2" size="4"/></label>
<label>W <input type="text" name="w" id="w" size="4"/></label>
<label>H <input type="text" name="h" id="h" size="4"/></label>
</div>
<div style="margin:5px;">
<input type="submit" value="Crop Image" />
</div>
</form>
<p>
<b>An example of crop script.</b> I decided to show form with values (you can keep it invisible if you want).
Current sample ties several form values together with a event handler.
Form values are updated as the selection is changed.
Also current sample have preview area. So we will see our crop result.
Aspect ratio disabled.
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!
</p>
</div>
<h3><a href="#">Jcrop - Animations</a></h3>
<div class="sample_2">
<img src="files/image.jpg" id="cropbox2" />
<div style="margin: 20px 0;">
<button id="anim1">Position 1</button>
<button id="anim2">Position 2</button>
<button id="anim3">Position 3</button>
<button id="anim4">Position 4</button>
<button id="anim5">Position 5</button>
</div>
<p>
<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!
</p>
</div>
<h3><a href="#">Jcrop - Custom styling</a></h3>
<div class="sample_3">
<img src="files/image.jpg" id="cropbox3" />
<p>
<b>So maybe you like the color blue.</b>
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).
</p>
</div>
</div>
</div>

Step 2. CSS

Here are used CSS styles.

templates/css/jcrop_main.css

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.jcrop_example{background:#FFF;width:865px;font-size:80%;border:1px #000 solid;margin:3.5em 10% 2em;padding:1em 2em 2em}
.jcrop_example p{font-size:90%}
.accordion h3{margin:0}
.accordion form{border:1px solid;background:#E6E6E6;border-color:#C3C3C3 #8B8B8B #8B8B8B #C3C3C3;margin:.5em 0;padding:.5em}
.accordion form label{margin-right:1em;font-weight:700;color:#900;font-size:10px}
.jcrop_custom .jcrop-vline,.jcrop_custom .jcrop-hline{background:#FF0}
.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

$(function(){
// for sample 1
$('#cropbox1').Jcrop({ // we linking Jcrop to our image with id=cropbox1
aspectRatio: 0,
onChange: updateCoords,
onSelect: updateCoords
});
// for sample 2
var api = $.Jcrop('#cropbox2',{ // we linking Jcrop to our image with id=cropbox1
setSelect: [ 100, 100, 200, 200 ]
});
var i, ac;
// A handler to kill the action
function nothing(e) {
e.stopPropagation();
e.preventDefault();
return false;
};
// Returns event handler for animation callback
function anim_handler(ac) {
return function(e) {
api.animateTo(ac);
return nothing(e);
};
};
// Setup sample coordinates for animation
var ac = {
anim1: [0,0,40,600],
anim2: [115,100,210,215],
anim3: [80,10,760,585],
anim4: [105,215,665,575],
anim5: [495,150,570,235]
};
// Attach respective event handlers
for(i in ac) jQuery('#'+i).click(anim_handler(ac[i]));
// for sample 3
$('#cropbox3').Jcrop({ // we linking Jcrop to our image with id=cropbox3
setSelect: [ 20, 130, 480, 230 ],
addClass: 'jcrop_custom',
bgColor: 'blue',
bgOpacity: .5,
sideHandles: false,
minSize: [ 50, 50 ]
});
});
function updateCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$('#x2').val(c.x2);
$('#y2').val(c.y2);
var rx = 200 / c.w; // 200 - preview box size
var ry = 200 / c.h;
$('#preview').css({
width: Math.round(rx * 800) + 'px',
height: Math.round(ry * 600) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
};
jQuery(window).load(function(){
$("#accordion").accordion({autoHeight: false,navigation: true});
});
function checkCoords() {
if (parseInt($('#w').val())) return true;
alert('Please select a crop region then press submit.');
return false;
};

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

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = $targ_h = 200;
$jpeg_quality = 90;
$src = 'files/image.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;
}
require_once('templates/jcrop_main.html');
?>

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!

SIMILAR ARTICLES

Bootstrap Forms

0 5
jQuery Mobile Lesson 6

0 5

33 COMMENTS

  1. Hmm, that’s interesting! I would search on Google to find other similar articles. Actually, I came across your blog on Google Blog Search. I’m going to add your RSS feed to my reader. Continue posting please!

  2. This is just what I am looking for. Thank you so much for sharing this. You just saved me from more hours of work. :)

    Great job!

    • Yes, sure, second param for imagejpeg function is:
      string filename
      so you can necessary file path here for result images.
      just remove header, and select necessary path

      • How we can apply the path give us an example. my script is
        if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
        $targ_w = $targ_h = 200;
        $jpeg_quality = 90;
        $dirName=”product_image/”;
        $src = $dirName.’thumb_’.$_REQUEST[‘Image’];
        $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;
        //header(“location:ptests.php”);
        }

      • Hi Pankaj,
        Firstly, be careful with variables
        $src = $dirName.’thumb_’.$_REQUEST[‘Image’];
        this is very unsafe. Never trust all incoming data – and always check and validate it.
        For example, you can use ‘strip_tags’ (just in case).
        Secondly, why do you use $_REQUEST if it was sent by ‘POST’ ? Change it to $_POST

  3. Hi. Your article is cool!!!

    I’d like to build a plagin to edit image which includes zooming, rotating and cropping;
    This plugin (jCrop) works Ok if you don’t rotate image. If you rotate, there are problems.
    I suppose second layer is not rotated.
    Can you give me help or advice how to fix this problem, please?

    • It seems that firstly will need to look at dev demo. Difficult to suggest without knowing how this work in your side. Why need rotate second layer? And which exactly second layer?

  4. #preview.css part code –> why 800 in ( width: Math.round(rx * 800) + ‘px’, ) and why 600 in (height: Math.round(ry * 600) + ‘px’) ???

  5. Hi, there’s a problem with your script when image size more than 800х600. the image contracts on width with distortions. HELP!!!)

  6. Hi Andrew, this is very nice!! and woks pretty well!! but i don’t know how to replace the variable $src… i mean, the image name will be always diferent… how could it be changed?? could you please give me an example… pff i am stuck on this!!! thank you very much!!!

    • Hi Dani,
      If you need to make images with unique names, you can use an easy trick:
      $sFileName = md5(uniqid(rand(), true));

    • Hello Selvi,
      Try to search for functions to work with images in ASP.NET. There should be some alternative of GD.

  7. Hello, your plugin is fab, but i am getting problem of jquery.jcrop.min.js file, when i integrate your code with my site, i get error “TypeError: pos is undefined”. Can you please tell me the reason and solution

    • Hi Redo,
      In order to work with database, you need to have some knowledge about databases (about types and how to work with different database types).

    • Hello Sunny,
      We don’t save the image while crop, but we process it only after, when you post the result to the server. Pay attention to the ‘index.php’ file: we do nearly everything here.

    • Hi Khoiruddin,
      Try to refresh the page (with our article). In case if you already shared it, instead of the sharing form you will see the unlocked button

  8. Hey,
    This is good. I am getting different image portion on update preview function than the cropped image. Could you tell me what might be the problem?

    Thanks

Leave a Reply