Php

Image Upload, Crop and Resize Using PHP, jQuery and Ajax

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 Result Using PHP and AJAX

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 folder, which is use to keep all library file.

Image Uploading, Cropping and Resizing with PHP and Ajax

Step 1: We will include all necessary jQuery plugin and library files. Let’s add all below files in 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 to show image and option to change image.

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

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

Related Post

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

<div id="changePic" class="" style="display:none">
                  <form id="cropimage" method="post" enctype="multipart/form-data" action="profile.php">
            <label>Upload your image</label><input type="file" name="photoimg" id="photoimg">
            <input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1">
            <input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="">
            <input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="">
            <input type="hidden" name="hdn-x2-axis" value="" id="hdn-x2-axis">
            <input type="hidden" name="hdn-y2-axis" value="" id="hdn-y2-axis">
            <input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="">
            <input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="">
            <input type="hidden" name="action" value="" id="action">
            <input type="hidden" name="image_name" value="" id="image_name">
            

<div id="preview-avatar-profile">
</div>


<div id="thumbs" style="padding:5px; width:600p"></div>

          </form>

<div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                  <button type="button" id="btn-crop" class="btn btn-primary">Crop & Save</button>
</div>

</div>

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.

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'],
                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('#change-pic').show();
        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: We will define controller/action method in profile.php.

/*********************************************************************
   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 "<img id="photo" class="" src="".getCustomAvatar($userId, true)." ?'.time()."'="">";
    }
    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

View Comments

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories