Skip to main content

Image Crop and Upload with jQuery and PHP

There are many good jQuery plugins are available  today to crop image on the fly. jCropimgAreaSelect and many more. Today I am going to show you how you can implement imgAreaSelect jQuery plugin for cropping image on your project with instant upload preview.

imgAreaSelect is one of the most powerful jQuery plugin for working with images that can work in all major old and new browser. It is easy to configure and implement.

Live Demo Download Source

HTML Image Uploading Form

As usual we will start with html markup. We need to create a simple file upload form with 4 hidden fields with blank value. These hidden fields will need to submit image selection values. We also need to add a img without src attribute. Image will be appear here for instant preview

<!-- image preview area-->
<img id="uploadPreview" style="display:none;"/>
  
<!-- image uploading form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
  <input id="uploadImage" type="file" accept="image/jpeg" name="image" />
  <input type="submit" value="Upload">

  <!-- hidden inputs -->
  <input type="hidden" id="x" name="x" />
  <input type="hidden" id="y" name="y" />
  <input type="hidden" id="w" name="w" />
  <input type="hidden" id="h" name="h" />
</form>

jQuery and JavaScript Part

The following jQuery and JavaScript code holds some imgAreaSelect configurations. We also need to use FileReader html5 file reader api to make instant image preview.

// set info for cropping image using hidden fields
function setInfo(i, e) {
  $('#x').val(e.x1);
  $('#y').val(e.y1);
  $('#w').val(e.width);
  $('#h').val(e.height);
}

$(document).ready(function() {
  var p = $("#uploadPreview");

  // prepare instant preview
  $("#uploadImage").change(function(){
    // fadeOut or hide preview
    p.fadeOut();

    // prepare HTML5 FileReader
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

    oFReader.onload = function (oFREvent) {
         p.attr('src', oFREvent.target.result).fadeIn();
    };
  });

  // implement imgAreaSelect plug in (http://odyniec.net/projects/imgareaselect/)
  $('img#uploadPreview').imgAreaSelect({
    // set crop ratio (optional)
    aspectRatio: '1:1',
    onSelectEnd: setInfo
  });
});

PHP Part

The following php code holds some basic download validation and php gd based image resize functionalities

$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
$max_file_size = 200 * 1024; #200kb
$nw = $nh = 200; # image with & height

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if ( isset($_FILES['image']) ) {
    if (! $_FILES['image']['error'] && $_FILES['image']['size'] < $max_file_size) {
      # get file extension
      $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
      # file type validity
      if (in_array($ext, $valid_exts)) {
          $path = 'uploads/' . uniqid()  . '.' . $ext;
          $size = getimagesize($_FILES['image']['tmp_name']);
          # grab data form post request
          $x = (int) $_POST['x'];
          $y = (int) $_POST['y'];
          $w = (int) $_POST['w'] ? $_POST['w'] : $size[0];
          $h = (int) $_POST['h'] ? $_POST['h'] : $size[1];
          # read image binary data
          $data = file_get_contents($_FILES['image']['tmp_name']);
          # create v image form binary data
          $vImg = imagecreatefromstring($data);
          $dstImg = imagecreatetruecolor($nw, $nh);
          # copy image
          imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
          # save image
          imagejpeg($dstImg, $path);
          # clean memory
          imagedestroy($dstImg);
          echo "<img src='$path' />";
          
        } else {
          echo 'unknown problem!';
        } 
    } else {
      echo 'file is too small or large';
    }
  } else {
    echo 'file not set';
  }
} else {
  echo 'bad request!';
}

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery . Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar. We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code . multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin . It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.