Resize or Crop Image before Upload Using HTML5 File API


I've always loved how Whatsapp, Facebook, Twitter and all the major social network platforms maintained sanity of uploaded profile pictures through the use of instant resize at upload time. Of course not only profile pictures need to be made to conform to a specific dimension, if you find other scenarios during development when you need to ensure that your images are of a specific height and width, or aspect ratio then this article will help you do just that. You may also just want to give the user ability to resize before final upload, this article will help you do just that.

Step 1: Download CropperJs Plugin
There are lots of plugins that could help to achieve our objective, and I've tried a few. I find this one very robust and easier to use. Here's the github link


Step 2: Import the CropperJs Plugin
Using your script tag, import the downloaded plugin's Javascript file and link the CSS file too. Note, that for speedy loading, CSS files should be loaded in the head section, while Javascript files should be loaded just before closing the BODY tag. Also ensure that JQuery library is included in your project.

<link href="css/cropper.css" rel="stylesheet" />
<script src="js/cropper.min.js"></script>


Step 3: Add Required HTML Tags

<input id="the-file-input" type="file" accept="image/*">
<div id="PreviewImage"></div>
<button type="button" id="SaveImageBtn" >Save Image</button>

  • The file input control with Id = the-file-input will be used to select the image
  • The div with id = PreviewImage will be the cropping area
  • The button with id = SaveImageBtn will be used to trigger the upload process

Step 3:  Add JavaScript Code


InitializeCropper = function () {
        $WorkingImage = $("#ImageToCrop");        
        var CropperSize = 200; //size of the crop box
        $WorkingImage.cropper({
            aspectRatio: 1 / 1, //aspect ratio of the crop box
            data: {
                width: CropperSize,
                height: CropperSize
            }
        });
    }

function renderImage(file) {
        var reader = new FileReader();
        reader.onload = function (event) {
            the_url = event.target.result
            $('#PreviewImage').html("<img id='ImageToCrop' src='" + the_url + "' />")
            InitializeCropper();
        }
        reader.readAsDataURL(file);
    }

$(document).ready(function(){
  $("#the-file-input").change(function () {
            renderImage(this.files[0])
        });

        $('#SaveImageBtn').click(function () {
            var ImageDataURL = $WorkingImage.cropper('getCroppedCanvas').toDataURL('image/jpeg');
            //SaveImageURL(ImageDataURL);
        });
});

Remember that your JavaScript code needs to be enclosed in script tags if they are within your HTML.

Step 4: Save Your Cropped Image
If you open your HTML file in the browser, at this point, you should be able to select an image file and crop as desired. The next step required is to upload cropped image and save in the server. Notice the SaveImageURL method called above inside the SaveImageBtn click event? Its commented out, but that's where the uploading takes place. The image DataURL string will be sent to the server through an Ajax call. I will provide sample codes for Client and Server side in my next post. Meanwhile, enjoy this cropping process first.

This method is in use within a live project at http://www.osigla.com.ng/clinical/

Cheers.

Comments

Popular posts from this blog

Exception from HRESULT: 0x80131040

Get Creative With Data Tables: Row Click Events