Crop and save image using jquery and php

by Vincy. Last modified on July 15th, 2022.

In a previous article, we have seen the PHP code for cropping images using jQuery. In that example, the landing page loads a static image element which is turned into a crop-able layer by using Jcrop library.

After publishing the PHP crop example, many of the readers asked to publish an article with an example to implement cropping with the dynamically uploaded images. Here you go, let us create the PHP example to upload an image and show its preview and enable cropping feature on it.

For making this code more simple, we have to merge the PHP file upload example and the jQuery image cropping example together. So, a form with file upload option is used to choose the image file and upload the file binary to the PHP code.

In the PHP file, the $_FILES array data is received and uploaded file is moved to the specified target. On successful upload, the image preview is shown and the cropping functionality is initialized with the reference of the preview element.

Crop and save image using jquery and php

HTML Form with Image Upload Option

This code is used to create an HTML form with the file input to let the user choose and upload the image file. If you want image upload with AJAX, then download the source code from the PHP AJAX image upload article.

After processing the PHP image upload script, the uploaded image preview is shown with an HTML image element. This element reference is used to initialize the Jcrop library options.



PHP Image Upload Code

This is the usual file upload code in PHP that is very familiar to us as we have seen in many file upload examples. The PHP move_uploaded_file function moves the uploaded file to the specified target. Once the image upload is completed, then the PHP code will show the preview of the uploaded image.


jQuery Based Jcrop Library Initialization to Enable Cropping

Instead of referring to the static image element, the Jcrop is initialized with the dynamically uploaded image. The uploaded image preview is referred with an id attribute. This id is later used in the jquery script to initialize the jCrop library properties to call cropping function. It enables the cropping feature on the preview image element loaded dynamically on image upload.


Download

↑ Back to Top

In This article, I will let you know how to do Image uploading, cropping, and resizing using PHP and Ajax.We have earlier post an article image upload and crop using popup box .I got a huge response from all of you guys. There are a lot of folks who request to share articles about image crop and resizing without popup box or modal box. Sometimes popup boxes create issues on tablet and mobile devices.

In this post, I will demonstrate image uploading and cropping on the same page instead of a modal box. We are showing and hiding image view div based on user action. I am using PHP GD library for resizing images and AJAX Form jquery plugin for image upload using AJAX manner. I am using Imgareaselect plugin to crop image and PHP for resizing image with save cropped image.

There are following jQuery plugin and CSS Library Used into this tutorial –

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

Also Checkout other tutorial of image crop,

  • Image Crop Functionality In Model Box Using PHP
  • Image Upload, Crop and Resize Using PHP, jQuery and Ajax

Crop and save image using jquery and php

Here, I am showing default.jpg image file for as a default image.

Step 3: Let’s create a div to upload and crop image.


Step 4: Added some jQuery code to show the Image Crop div on click of change-pic button.

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

The above code will show the uploaded image container div where you will crop and save images, I also hide the change Pic button.

Step 5: We will use the jQuery Ajax form plugin for form submitting and show the image for the crop process on the page.

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 on 'success' call back function.

Sponsored Links

Step 6: Added jQuery code to cropped image and called save Ajax method to save image on hard disk storage.

  //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'],
                h2: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('#change-pic').show();
        jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
        
        jQuery("#avatar-edit-img").attr('srx', 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: We will define controller/action method in profile.php.

Sponsored Links

/*********************************************************************
   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 : '',
            ));
            
    echo "";
    }
    else
    echo "failed";
    }
    else
    echo "Image file size max 1 MB"; 
    }
    else
    echo "Invalid file format.."; 
    }
    else
    echo "Please select image..!";
    exit;
    
    
  }

Step 8: Model method to save image path into database.

/*********************************************************************
   Purpose      : save avatar.
   Parameters       : $options 
   Returns      : true/false
   ***********************************************************************/
  function saveAvatar($options){
     $con=mysqli_connect("localhost","my_user","my_password","my_db");
     // Check connection
    if (mysqli_connect_errno())
     {
       echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

      //update sql
      $sql = "UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'";
      mysqli_query($con, $sql);
    }

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