• HTML/CSS
  • jQuery
  • PHP
  • JS
  • AJAX
  • MySQL
  • Res
  • XSLT
  • Contact Us
  • HTML/CSS
    • Game Development →
      • HTML5 Game Development - Lesson 1
      • HTML5 Game Development - Lesson 2
      • HTML5 Game Development - Lesson 3
      • HTML5 Game Development - Lesson 4
      • HTML5 Game Development - Lesson 5
      • HTML5 Game Development - Lesson 6
      • HTML5 Game Development - Lesson 7
    • Menus →
      • CSS3 multilevel menu with transition and animation
      • Marble Style CSS3 Navigation Menu
      • Toggle CSS3 Bottom Navigation Bar
      • Accordian like CSS3 Onclick Vertical Navigation
      • Multilevel CSS3 Metal Navigation with icons
      • Click-action CSS3 Dropdown Menu with jQuery
      • Click action Multi-level CSS3 Dropdown Menu
      • CSS3 Animated Menu
      • CSS3/jQuery crossbrowser Drop-down menu with tabs
      • CSS3 Drop sliding list Menu #6
      • CSS3 Slideout Menu #5
      • CSS3 Dropdown Menu #4
      • CSS3 Dropdown Menu #3
      • CSS3 Dropdown Menu #2
      • Cool CSS3 Dropdown Menu
    • Templates →
      • Robo Splash Page Layout
      • 'Mono' HTML5 CSS3 Single Page Layout
      • HTML5/CSS3 single page layout - Art theme
      • Attractive HTML CSS Anime Theme Website Layout
      • HTML CSS website layout #4 - Gray theme
      • Dark and clean HTML CSS website layout
      • HTML5&CSS3 single page layout - Rock portal
      • E-Store HTML5 CSS3 Single Page Layout
      • Under Water Themed HTML5 & CSS3 single page Layout
      • HTML5 & CSS3 Single Page Web Layout
    • HTML5 tutorials →
      • HTML5 Canvas Slideshow
      • HTML5 canvas - Custom brush #2 (Bubble brush)
      • HTML5 canvas - Custom brush (BezierCurveBrush)
      • HTML5 Face Builder
      • Pure HTML5 file upload
      • HTML5 image crop tool
      • HTML5 animation - patterns with loops
      • HTML5 3D circle text with shadows
      • HTML5 canvas pixelate effect
      • Animated Moving Clouds using HTML5
      • Animated Fireplace in HTML5
      • 3D Animated Box HTML5 WebGL Photo Slideshow
      • Your Own Paint Program
      • Image Zoomer in HTML5 Canvas
      • Photo Array in WebGL
      • HTML5 Canvas Image Color Picker
      • HTML5 Image Effects App - Adding Horizontal Flip
      • Keyboard Sensitive 3D Twisted Images in WebGl
      • Animated 3D WebGL Demonstration
      • HTML5 Image Effects App - Adding Noise and Invert
      • HTML5 Canvas Image Effects App - Adding Blur
      • Attractive Presentation with HTML5
      • HTML5 Canvas App for Online Image Enhancements
      • Water Ripple effect using HTML5 canvas
      • Animated 3D canvas object in HTML5
    • CSS3 tutorials →
      • CSS3 Image Hover Effects
      • CSS3 Modal Popups
      • Isometric interactive interior guide
      • Analog Clock with Pure CSS3
      • CSS3 Optical Illusions
      • CSS3 Animated Photo Slider
      • CSS3 Christmas Tree with Snow
      • How to Create a Pure CSS3 Slideshow
      • CSS3 Drop Caps
      • Pure CSS3 Slider
      • Fantastic Animated Buttons using CSS3
      • How to Create a Pure CSS3 Animated Photo Gallery
      • Toggle CSS3 Bottom Navigation Bar
      • How to Generate Runtime Multi-columns with CSS3
      • Multiple backgrounds and Animation with CSS3
  • jQuery
    • Photo album with jQuery Fotorama
    • Photo album with jQuery Chop Slider
    • Cool Background Image Sliding effect with jQuery
    • jQuery Templates - Usage Practice
    • Photo Album with Galleriffic jQuery plugin
    • Fantastic Photo Album with TN3
    • Ajaxy Photo Gallery (jQuery) with Custom Images Sets
    • Rotating Slider with Easing Effects in jQuery
    • Animated jQuery Progressbar Plugin
    • Nice CSS3 Lightbox Gallery
    • Photo Album with Highslide
    • Using Flux Slider jQuery plugin
    • Ajaxy Chained Selects
    • Modern jQuery Pagination for Content
    • Your own jQuery Slider Plugin
    • Attractive Photo Gallery using SmartGallery
    • Animated Photo Gallery using jQuery (Slider Kit)
  • PHP
    • Powerful Chat System - Lesson 3
    • Powerful Chat System - Lesson 2
    • Powerful Chat System
    • Access Control with Bit Masks
    • Own XML/JSON/HTML API with PHP
    • Your Own Ajax Poll System
    • Diary style PHP Guestbook
    • Smooth Curve Graphs with PHP and GD
    • Your Own Commenting System from Scratch
    • Autocomplete with PHP, jQuery, MySQL and XML
    • Your Own 5 Stars Voting System
    • How to use Memcache with PHP
    • How to install APC on Linux
    • How to Use APC Caching with PHP
    • Watermark processing on images using PHP and GD
    • ID3 Tags Reader with PHP
    • Advance Level Login system with Logic captcha
    • Protection and Methodologies of Security Vulnerabilities
    • How to Resize images on Server Side
    • How to Protect any Site from Spam using Akismet
    • Phar - PHP archiving practice
  • JS
    • Form Validation with Javascript and PHP
    • Fullscreen Javascript Slide navigation
    • Photo Scrambler grid in javascript
    • Photo Slideshow (zoom fading) effect
    • Custom scrollbars - cross-browser solution
    • Flare Lens Effect
    • Own RSS Reader Using Google Feed API
    • Cross-browser Wave Effects
    • Cross-browser Supported Image Skew effect
  • Res
    • ← Infographic
      • The Evolution of Languages
    • ← jQuery plugin roundups
      • December 2011
      • November 2011
      • 10 fresh jQuery Tutorials
      • October 2011
      • September 2011
      • 10 fresh Ajax related jQuery plugins
      • August 2011
      • 10 Oven Fresh jQuery Plugins for UI
      • 10 Most creative jQuery plugins for tables
      • 10 Most Creative jQuery Navigation Plugins
      • 10 fresh jQuery plugins for working with forms and UI
      • 10 superb jQuery plugins for working with images
    • ← HTML5 stuff
      • HTML5 and Games
      • 10 Fresh HTML5 Tutorials
      • Fresh impressing WebGL demonstrations
      • Most impressing HTML5 with WebGL demonstrations
      • 10 Fresh & Impressive HTML5 Canvas (and WebGL) Examples
      • 10 Exceptional Examples of HTML5 Canvas and Applications
    • ← Mobile
      • How to start developing own applications for Android
      • 10 Fresh Android tutorials
      • 10 Attractive Tutorials for Developing iPhone Applications
      • 10 Attractive android tutorials for developers
      • 10 Fresh iPad Apps for Web Designers & Developers
      • 10 Fresh Android Apps for Web Designers & Developers
      • 10 Fresh iPhone Apps for Web Designers & Developers
      • Top 10 iPhone apps for working with graphics
    • 12 Unique Navigation Menu Designs For Your Inspiration
    • 15 Unique and Creative Layouts 2011
    • 12 Beautifully Creative Flash Websites of 2011
    • Fresh collection of Original Captchas
  • XSLT
    • Animated forums using XSLT and Ajaxy
    • Multilevel Menu using XSLT
    • Delicious bookmarks using XSLT transformation
    • XPath visually
    • Tags cloud using XSLT transformation
    • Youtube videos using XSLT transformation
  • Contact Us
KEEP IN TOUCH

Cropping images in runtime using Jcrop (jQuery)

Sep01
2010
24 Comments Written by admin

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!

About: admin:
I am web developer with huge experience (in web languages and even in system languages). Also I am the founder of current website (and several another). I like to write blogs about web development/design. Feel free to Follow us on Twitter: tweetmeme_screen_name='AramisGC';
If you Enjoyed our article don't forget to Share the love with your friends.
    Tweet
   
   
Written by: admin on September 1, 2010.

Related Stuff You Will Love!

  1. How to Translate your Site in Runtime using jQuery
    How to Translate your Site in Runtime using jQuery
  2. Creating Ajax based file uploaders
    Creating Ajax based file uploaders
  3. 10 superb jQuery plugins for working with images
    10 superb jQuery plugins for working with images
  4. Creating Ajaxy Photo Gallery (jQuery) with Custom Images Sets
    Creating Ajaxy Photo Gallery (jQuery) with Custom Images Sets
Posted in HTML/CSS, JavaScript, jQuery, PHP - Tagged crop images, cropping, images, Jcrop, jQuery, online, website
SHARE THIS Twitter Facebook Delicious StumbleUpon E-mail
« Importing multiple RSS feeds – using newsWidget (jQuery)
» Easily Animate Web Buttons/Objects using jQuery

10 Comments

  1. annuaire gratuit's Gravatarannuaire gratuit
    September 15, 2010 at 9:20 pm | Permalink

    I’ve send this page to my fb friends. Keep this good work :)

  2. jordans's Gravatarjordans
    September 18, 2010 at 2:20 am | Permalink

    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!

  3. Abby's GravatarAbby
    October 24, 2010 at 3:29 pm | Permalink

    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!

  4. SkiX's GravatarSkiX
    February 19, 2011 at 12:12 pm | Permalink

    Hi, is it possible to auto save croped picture?

  5. admin's Gravataradmin
    February 19, 2011 at 5:05 pm | Permalink

    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

  6. Abdurahman's GravatarAbdurahman
    April 21, 2011 at 12:09 pm | Permalink

    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?

  7. admin's Gravataradmin
    April 22, 2011 at 3:38 am | Permalink

    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?

  8. Rqton's GravatarRqton
    May 10, 2011 at 3:16 pm | Permalink

    thx! Very helpful :)

  9. dotnetflavors's Gravatardotnetflavors
    November 18, 2011 at 10:59 am | Permalink

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

  10. admin's Gravataradmin
    November 21, 2011 at 7:28 am | Permalink

    Thanks for sharing this tutorial

3 Trackbacks

  1. Web Script Den » Blog Archive » Cropping images in runtime using Jcrop (jQuery) – www.script … on September 1, 2010 at 3:26 pm
  2. Cropping images in runtime using Jcrop (jQuery) – www.script … | Web Scripts Maniacs on September 1, 2010 at 4:07 pm
  3. Cropping images in runtime using Jcrop (jQuery) – www.script … « Web Script Genie on September 1, 2010 at 6:19 pm
  4. Cropping images in runtime using Jcrop (jQuery) » WB Tips on September 1, 2010 at 7:31 pm
  5. Tweets that mention Cropping images in runtime using Jcrop (jQuery) -- Topsy.com on September 2, 2010 at 6:38 am
  6. Cropping images in runtime using Jcrop (jQuery) : Speckyboy Design Magazine on September 14, 2010 at 8:15 am
  7. 160+ Awesome Articles for Web Designers and Developers — tripwire magazine on September 15, 2010 at 5:28 am
  8. 160+ Awesome Articles for Web Designers and Developers | The best Tutorials on September 15, 2010 at 5:41 am
  9. Cropping images in runtime using Jcrop (jQuery) | Scriptsnthings.com on September 15, 2010 at 5:46 am
  10. Easily Animate Web Buttons/Objects using jQuery | Scriptsnthings.com on September 15, 2010 at 5:47 am
  11. 160+ Awesome Articles for Web Designers and Developers | Prabaharan CS Blog on September 15, 2010 at 6:43 pm
  12. educational toys on October 5, 2010 at 7:25 am
  13. saskatoon escorts on November 22, 2010 at 12:28 am
  14. Episode Guide on December 26, 2010 at 11:17 am

Leave a Reply Cancel 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>

Popular Tutorials

  • How to create easy pagination with jQuery
  • Animated jQuery Progressbar Plugin
  • Pure HTML5 file upload
  • Creating a HTML5 & CSS3 Single Page Web Layout
  • HTML5 Game Development – Lesson 6
  • How to Create Animated Photo Gallery using jQuery (Slider Kit)
  • Developing Your First HTML5 Game – Lesson 1
  • How to Easily Make a PHP Chat Application

Tags

3d AJAX android animated animation app application applications apps canvas captcha chat system coding creating css css3 developers effect effects flash fresh gallery how-to html html5 image images iphone javascript jQuery layout menu navigation new photo PHP plugin plugins slideshow system tutorial tutorials webgl website xslt

Recent Tutorials

  • Infographic: The Evolution of Languages
  • 12 Unique Navigation Menu Designs For Your Inspiration
  • Form Validation with Javascript and PHP
  • 10 fresh jQuery plugins (january 2012)
  • Powerful Chat System – Lesson 3
  • Invoicera offer results
  • CSS3 Image Hover Effects
  • HTML5 Canvas Slideshow

Friends

  • X-Musics

Tutorials for Web Developers Copyright © 2009-2011 Script tutorials · All rights reserved