Image Crop Functionality In Model Box Using PHP

Image uploading and cropping is very common functionality for any web application.You can upload and crop image on same page or in modal box.In this PHP article, I am sharing Demo and Source Code to upload and cropped image using PHP and jQuery. There are a lot of image cropping jquery plugin available.

Normally, We are given image/picture change functionality to end user, So user can upload and crop image.This is awesome user experience to give image change and cropping in modal box.I am using bootstrap Modal box to show upload image option.

There are following jQuery plugin and CSS Library Used

  • jQuery Library : Base library to support other jquery plugin.
  • Bootstrap 3 : Used to create awesome HTML layout to image upload and submit.
  • Imgareaselect : Use to define crop co-ordinate and crop image,You can download from here.
  • Ajax form : Use to submit form Ajax manner, You can download from here.

In This article, I am using Imgareaselect plugin to crop image and PHP for resizing image and save cropped image.

There are Following files will participate in this image crop tutorial

  • index.php : This file is responsible to create HTML layout and show cropped image.
  • profile.php : This file is responsible to all server side functionality like image cropping and saving
  • dist : This is a libs folder, which is use to keep all third party library files.

Also Checkout other tutorial of image crop,

Image Upload and Cropping with PHP and jQuery

Step 1: First, We will include all necessary jquery plugin and library files.We will keep all below files into head section of index.php file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="dist/jquery.imgareaselect.js" type="text/javascript"></script>
<script src="dist/jquery.form.js"></script>

Step 2: We will Create div container to show image and option to change image.

<div>
   <img id="avatar-edit-img" class="img-circle" style="width: 140px; height: 140px;" src="default.jpg" height="128" data-src="default.jpg" data-holder-rendered="true"> 
   <a id="change-pic" class="btn btn-primary" type="button"></a>Change Image
</div>

Here, I am displayingdefault.jpg image file as a default image of profile page.

Step 3: Let’s create model box to upload and crop image.

<!--model box -->
<div id="changePic" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"><button class="close" type="button" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Change Profile Picture</h3>
</div>
<div class="modal-body"><form id="cropimage" action="profile.php" enctype="multipart/form-data" method="post">Upload your image <input id="photoimg" name="photoimg" type="file"> <input id="hdn-profile-id" name="hdn-profile-id" type="hidden" value="1"> <input id="hdn-x1-axis" name="hdn-x1-axis" type="hidden" value=""> <input id="hdn-y1-axis" name="hdn-y1-axis" type="hidden" value=""> <input id="hdn-x2-axis" name="hdn-x2-axis" type="hidden" value=""> <input id="hdn-y2-axis" name="hdn-y2-axis" type="hidden" value=""> <input id="hdn-thumb-width" name="hdn-thumb-width" type="hidden" value=""> <input id="hdn-thumb-height" name="hdn-thumb-height" type="hidden" value=""> <input id="action" name="action" type="hidden" value=""> <input id="image_name" name="image_name" type="hidden" value="">
<div id="preview-avatar-profile"> </div>
<div id="thumbs" style="padding: 5px; width: 600p;"> </div>
</form></div>
<div class="modal-footer"><button class="btn btn-default" type="button" data-dismiss="modal">Close</button> <button id="btn-crop" class="btn btn-primary" type="button">Crop & Save</button></div>
</div>
</div>
</div>

Step 4: Added some jQuery code to show the model box.The user will click change pic button and display the modal box.

jQuery('#change-pic').live('click', function(e){
		e.preventDefault();
		
		jQuery('#changePic').show();
		
	});

As You cann see above code, We are popup image upload bootstrap modal box on click of Change Image.

Step 5: Create jQuery Ajax form plugin for form submitting and show the image for crop process on bootstrap modal box.

jQuery('#photoimg').live('change', function()	
{ 
jQuery("#preview-avatar-profile").html('');
jQuery("#preview-avatar-profile").html('Uploading....');
jQuery("#cropimage").ajaxForm(
{
target: '#preview-avatar-profile',
success:    function() { 
        jQuery('img#photo').imgAreaSelect({
        aspectRatio: '1:1',
        onSelectEnd: getSizes,
    });
    }
}).submit();
});

You can get image all parameters into the 'success' call back function.

Step 6: We will cropped image and call save Ajax method to save image on hard disk storage.

//fucntion for get image cropped co-ordinate
function getSizes(img, obj)
	{
		var x_axis = obj.x1;
		var x2_axis = obj.x2;
		var y_axis = obj.y1;
		var y2_axis = obj.y2;
		var thumb_width = obj.width;
		var thumb_height = obj.height;
		if(thumb_width > 0)
			{

				jQuery('#hdn-x1-axis').val(x_axis);
				jQuery('#hdn-y1-axis').val(y_axis);
				jQuery('#hdn-x2-axis').val(x2_axis);
				jQuery('#hdn-y2-axis').val(y2_axis);
				jQuery('#hdn-thumb-width').val(thumb_width);
				jQuery('#hdn-thumb-height').val(thumb_height);
				
			}
		else
			alert("Please select portion..!");
	}
	//call on crop iamge button
jQuery('#btn-crop').live('click', function(e){
	e.preventDefault();
	params = {
            targetUrl: 'profiles/saveAvatarTmp/',
            action: 'profiles_controller_saveAvatarTmp',
			x_axis: jQuery('#hdn-x1-axis').val(),
			y_axis : jQuery('#hdn-y1-axis').val(),
			x2_axis: jQuery('#hdn-x2-axis').val(),
			y2_axis : jQuery('#hdn-y2-axis').val(),
			thumb_width : jQuery('#hdn-thumb-width').val(),
			thumb_height:jQuery('#hdn-thumb-height').val()
        };
		saveCropImage(params);
	});
	//make ajax request to PHP for save image
function saveCropImage(params) {
    jQuery.ajax({
        url: siteurl + params['targetUrl'],
        cache: false,
        dataType: "html",
        data: {
            action: params['action'],
            id: jQuery('#hdn-profile-id').val(),
			 t: 'ajax',
								w1:params['thumb_width'],
								x1:params['x_axis'],
								h1:params['thumb_height'],
								y1:params['y_axis'],
								x2:params['x2_axis'],
								y2:params['y2_axis']
        },
        type: 'Post',
       // async:false,
        success: function (response) {
				jQuery("#changePic").hide();
				jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
				
				jQuery("#avatar-edit-img").attr('src', response);
				jQuery("#preview-avatar-profile").html('');
				jQuery("#photoimg").val();
				AlertManager.showNotification('Image cropped!', 'Click Save Profile button to save image.', 'success');
				
				
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
        }
    });
	}
	
	

Step 7: Now define controller and action method into the profile.php file.

/*********************************************************************
	 Purpose			: update image.
	 Parameters		    : null
	 Returns			: integer
	 ***********************************************************************/
	public function changeAvatar() {
		global $current_user;
		$loggedInId = $current_user->ID;
		$post = isset($_POST) ? $_POST: array();
		$max_width = "500";	
		$userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0;
		$path = get_theme_root(). '\images\uploads\tmp';

		$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
		$name = $_FILES['photoimg']['name'];
		$size = $_FILES['photoimg']['size'];
		if(strlen($name))
		{
		list($txt, $ext) = explode(".", $name);
		if(in_array($ext,$valid_formats))
		{
		if($size<(1024*1024)) // Image size max 1 MB
		{
		$actual_image_name = 'avatar' .'_'.$userId .'.'.$ext;
		$filePath = $path .'/'.$actual_image_name;
		$tmp = $_FILES['photoimg']['tmp_name'];
		
		if(move_uploaded_file($tmp, $filePath))
		{
		$width = $this->getWidth($filePath);
			$height = $this->getHeight($filePath);
			//Scale the image if it is greater than the width set above
			if ($width > $max_width){
				$scale = $max_width/$width;
				$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
			}else{
				$scale = 1;
				$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
			}
		$res = $this->Profile->saveAvatar(array(
						'userId' => isset($userId) ? intval($userId) : 0,
												'avatar' => isset($actual_image_name) ? $actual_image_name : '',
						));
						
		//mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
		echo "<img id="photo" class="" src="".getCustomAvatar($userId, true).">";
		}
		else
		echo "failed";
		}
		else
		echo "Image file size max 1 MB"; 
		}
		else
		echo "Invalid file format.."; 
		}
		else
		echo "Please select image..!";
		exit;
		
		
	}
	/*********************************************************************
	 Purpose			: update image.
	 Parameters		    : null
	 Returns			: integer
	 ***********************************************************************/
	public function saveAvatarTmp() {
		global $current_user;
		$loggedInId = $current_user->ID;
		$post = isset($_POST) ? $_POST: array();
		$userId = isset($post['id']) ? intval($post['id']) : 0;
		$path = get_theme_root(). '\\images\uploads\tmp';
		$t_width = 300;	// Maximum thumbnail width
		$t_height = 300;	// Maximum thumbnail height

	if(isset($_POST['t']) and $_POST['t'] == "ajax")
	{
		extract($_POST);
		
		$img = get_user_meta($userId, 'user_avatar', true);
		$imagePath = $path.'/'.$img;
		$ratio = ($t_width/$w1); 
		$nw = ceil($w1 * $ratio);
		$nh = ceil($h1 * $ratio);
		$nimg = imagecreatetruecolor($nw,$nh);
		$im_src = imagecreatefromjpeg($imagePath);
		imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w1,$h1);
		imagejpeg($nimg,$imagePath,90);
		
	}
	echo getCustomAvatar($userId, true);
	exit(0);	
	}
	
	/*********************************************************************
	 Purpose			: resize image.
	 Parameters		    : null
	 Returns			: image
	 ***********************************************************************/
	function resizeImage($image,$width,$height,$scale) {
	$newImageWidth = ceil($width * $scale);
	$newImageHeight = ceil($height * $scale);
	$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
	$source = imagecreatefromjpeg($image);
	imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
	imagejpeg($newImage,$image,90);
	chmod($image, 0777);
	return $image;
}
/*********************************************************************
	 Purpose			: get image height.
	 Parameters		    : null
	 Returns			: height
	 ***********************************************************************/
function getHeight($image) {
	$sizes = getimagesize($image);
	$height = $sizes[1];
	return $height;
}
/*********************************************************************
	 Purpose			: get image width.
	 Parameters		    : null
	 Returns			: width
	 ***********************************************************************/
function getWidth($image) {
	$sizes = getimagesize($image);
	$width = $sizes[0];
	return $width;
}

Step 8: We will create Model method to save image path into the database.That help to retrieve cropped image and display into the page.

/*********************************************************************
	 Purpose			: save avatar.
	 Parameters		    : $options 
	 Returns			: true/false
	 ***********************************************************************/
	function saveAvatar($options){
  		//update sql

  	}

Image Crop Result Using PHP and AJAX

Demo & Download Source Code Of Image Cropping with PHP and AJAX

23 thoughts on “Image Crop Functionality In Model Box Using PHP

    • i am implementing your code in my codeigniter project, please suggest how to add get_user_meta() in my class or file of codeigniter project.

      • actually, i am using wordpress so that get_user_meta() getting undefined for non wordpress cms, this fucntion return user avatar name.You can get define constant as well.get more information about wordpress method https://codex.wordpress.org/Function_Reference/get_user_meta

  1. there is jquery plugin for multiple upload file control, otherwise you can create your script to add multiple upload control using jQuery.
    Create a file upload div which has upload control and clone this div when user will click add more upload button.

  2. on print_R($post);die;

    Array
    (
    [hdn-profile-id] => 1
    [hdn-x1-axis] =>
    [hdn-y1-axis] =>
    [hdn-x2-axis] =>
    [hdn-y2-axis] =>
    [hdn-thumb-width] =>
    [hdn-thumb-height] =>
    [action] =>
    [image_name] =>
    )

    this error are shown and not load the image

    • you can store image path in table col and fetch that col val at run time and add with src image attribute.

Leave a Reply

Your email address will not be published.