Special Offer - Get $90 Discount and Host Your Dream Web Site @ Dreamhost for 1 Year Click Here. Promo Code SLJ345
Back To Top
WordPress Web Application Development
Develop Powerfull Web Applications Using Cutting Edge WordPress Development Techniques

Crop Images using PHP GD Library and Jquery Resize

on 2011/06/16 9:32 AM stored in: Uncategorized and tagged:

Crop Images using PHP GD Library and Jquery Resize

Cropping images is a widely used feature in modern web applications. You can upload resize and crop images according to your preferences and display in the web site. All these features are used in facebook site fo managing images. In this tutorial I’m going to explain how to crop an image dynamically using PHP GD library and jquery events. This tutorial is divided into 2 main sections as shown below.

 

Section 1 – Selecting the Cropping Area with Jquery Drag and Resize Events
Section 2 – Cropping the Selected Image with PHP GD Library

Demo and Download

Before you are going to read this long tutorial you might want to look at what we are going to develop using live example. so i have provided the demo and code download in the following links. Load the demo and drag the little div with a border anywhere u want and resize it using the arrow mark on the bottom. Once you have finished selecting the image part click the crop button.

Download Image Cropping Examples
Image Cropping Examples Demo

 

Selecting the Cropping Area with Jquery Drag and Resize Events

Before we create the user interface for selecting the cropping area of the image, i would like to give an introduction to jquery events used in this section. For this example we need to use jquery draggable event on a div and resize event on a div. Lets start by using simple examples.

 

How to Make an Element Draggable with Jquery

	$( "#resizable" ).draggable({ containment: "parent" });

Element can be made draggable by using the jquery draggable function. In the above example the element with id resizable is made draggable. You can use id,class or an element in the draggable method.

	$( ".resizable" ).draggable({ containment: "parent" });

In the above code all the elements that has the class resizable are made draggable.

	$( "p" ).draggable({ containment: "parent" });

In the above code all the paragraph elements are made draggable. I have used { containment: “parent” } parameter in all the drag examples given above. That ‘s means all the elements will be dragged inside it’s parent element. If its not specified the element can be dragged anywhere in the browser window.

 

How to Make an Element Resizable with Jquery

	$( "#resizable" ).resizable({ containment: "parent" });

Resizable function can be used to make elements resize. This function works as the same way as draggable function and id,class or element can be used.

Since we have the knowledge of the functionalities which needs to build the user interface lets move on to the html and javascript code for selecting image to crop.

 

Creating the Interface for Image Cropping

	<form id='frm' action='imagecrops.php' method='post' >
            <div id='parent_container' style=''>

		
                <img src="test.jpg" id='crop_img'/>

		
                <div id="resizable"></div>

		
                <input type='hidden' name='img_width' id='img_width' />
                <input type='hidden' name='img_height' id='img_height' />
                <input type='hidden' name='source_x' id='source_x' />
                <input type='hidden' name='source_y' id='source_y' />


                <input type="submit" value='Crop' />
            </div>
        </form>

 

  • In the above code form is used to submit image cropping details to the php file.
  • Next line contains the image used fro cropping.You can dynamically load a image to this page.
  • Then i have defined a div called resizeble. This div can be dragged and resized inside the image to define the cropping area. Image part inside this div will be cropped on form submission.
  • Next 4 hidden fields is used to pass the new image width,height and the x,y coordinates of the image to be cropped.

 

Jquery Code for Crop Interface

	    $(document).ready(function() {
                $("#resizable").resizable({ containment: 'parent' });
                $( "#resizable" ).draggable({ containment: "parent" });

                var img_width = $('#crop_img').width();
                var img_height = $('#crop_img').height();
                $("#parent_container").width(img_width);
                $("#parent_container").height(img_height);


            });
            $(document).ready(function() {
                $('#frm').submit(function() {
                    var position = $('#resizable').position();
                    var position_img = $('#crop_img').position();


                    $('#img_width').val($('#resizable').width());
                    $('#img_height').val($('#resizable').height());
                    $('#source_x').val(position.left-8);
                    $('#source_y').val(position.top - 8);
                });
            });

 

  • First 2 lines of code makes the div with the id=resizable, draggable and resizable inside it’s parent container (parent_container div).
  • Then the image with and height is calculated and width,height of the parent container is adjusted according to that.
  • Next section contains the onsubmit method for the form.
  • On submission width,height of the new image and x,y coordinates of the starting position is calculated and assigned to hidden variables.
  • Then you can submit the form and image will be cropped using php as shown in the next section

Cropping the Selected Image with PHP GD Library

Like we did in the previous section lets have an introduction to the PHP Gd Library and gd functions used in this example before moving onto cropping the image.
PHP GD Library is used to process image handling functions in php. It provides extensive functionality to create,edit images. php imagecopy is the main function we are going to use in this example. This function allows you to copy one image inside a another image. In this example we are going to copy part of the image and paste into a new image with the cropped width and height using imagecopy function.

 

Using imagecopy Function

	imagecopy($dest, $src, 0, 0, $source_x, $source_y, $image_width, $image_height);

 

  • $dest is the destination image. Since we are trying to crop an image destination image size should be equal to the cropped size.
  • $src is the original image we want to crop. It should be in it’s original size.
  • Next 2 parameters are the coordinates to start on the destination image. Since we are cropping the part of image completely to the destination it should be 0,0.
  • Next 2 parameters are the starting coordinates of the cropped image part.
  • Last 2 parameters contain the height and width of the cropped image.

 

Crop the Image using GD Library Functions

    // Get the width and height of image to crop
    $image_width  = $_POST['img_width'];
    $image_height = $_POST['img_height'];

    // Starting cordinates of the original image
    $source_x = $_POST['source_x'];
    $source_y = $_POST['source_y'];

    // Create jpeg image from the src image
    $src = imagecreatefromjpeg('test.jpg');
	
    // Create a new image to paste the cropped image part
    $dest = imagecreatetruecolor($image_width, $image_height);

    // Copy the image to destination
    imagecopy($dest, $src, 0, 0, $source_x, $source_y, $image_width, $image_height);

    // Output and free from memory
    header('Content-Type: image/jpeg');
    imagejpeg($dest);

    imagedestroy($dest);
    imagedestroy($src);
  • First 2 lines of the above code will get the dimensions of the div used in the selection of the cropping area.
  • Next 2 lines will get the starting coordinates of the original image by using the top left position of the moving div.
  • Since we are using jpg in this example we can use imagecreatefromjpeg method to load the original image as source image.
  • Then we create a new destination image using imagecreatetruecolor function.
  • Next we copy the selected part to destination image as the cropped image using imagecopy function.
  • Then we can output the image to the browser and destroy both images.

Whats Next ?

In this example we used jpg images for cropping. You can use other gd library functions to crop other types of images as shown in below examples.

 

Using a png Image for Cropping

	imagecreatefrompng('test.png');

	header('Content-Type: image/png');
    	imagepng($dest);

 

Using a gif Image for Cropping

	imagecreatefromgif('test.gif');

	header('Content-Type: image/gif');
    	imagegif($dest);

In this php image manipulation tutorial i have only explained the basic functionalities needed to crop an image. You can extend this functions to build a fully featured dynamic image cropper application using jquery and php. Feel free to give your ideas or questions about this tutorial on the comment section.

Added Notes

Some of the users reported me that this example is not working properly in Google Chrome web browser. If you have any difficulties with regarding this please use the following code in the top of the script.

$(document).ready(function() {
                $('img').load(function() {
                $("#resizable").resizable({ containment: "parent" });
                $( "#resizable" ).draggable({ containment: "parent" });

                var img_width = $('#crop_img').width();
                var img_height = $('#crop_img').height();
                $("#parent_container").width(img_width);
                $("#parent_container").height(img_height);

                });
            });

Download EBook Version

InnovativePHP.com runs on Dreamhost

Dreamhost is a reliable web hosting server that enables you to host your dream web site. I have been using dreamhost for 1 year and experienced the most reliable customer support and most enhancing web features.

 

  • Unlimited Bandwidth
  • Unlimited Space
  • Unlimited Email Accounts and much more

 

Check out the complete Feature List and Sign Up for the 2 week Free Trial

Leave a Reply

Follow Us On Facebook