Cropping images in runtime using Jcrop (jQuery)

Date: 01st Sep 2010 Author: admin 13 Comments
Posted in: HTML/CSS, JavaScript, jQuery, PHP |Tags: , , , , , ,

Image Crop Plugin – using Jcrop (jQuery)

Due browsing web 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
download in package

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
download in package

Conclusion

Today I told you about new interesting jquery plugin – Jcrop. Sure that you will happy play with it. You can use this material to create own scripts into your startups. Good luck!

Enjoyed this Post?

    Tweet
   
   

Stay connected with us:

If you enjoyed this article, feel free to share our tutorial with your friends.

13 Comments

    • annuaire gratuit's Gravatar
    • jordans's Gravatar
    • 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!

    • Abby's Gravatar
    • 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!

    • SkiX's Gravatar
    • Abdurahman's Gravatar
    • 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?

    • Rqton's Gravatar
    • dotnetflavors's Gravatar
    • Hi friends see this link, it will useful for you.
      http://dotnetflavors.blogspot.com/2011/11/cropping-image-using-jquery.html

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

    • Zahoor Ahmad's Gravatar

Leave a Reply

Your email address will not be published. Required fields are marked *

*

CAPTCHA Image
Refresh Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>