[HTML5] Local Image Reading and Cropping with HTML5

  1. You need to use HTML5’s FileReader. Here, image-file is an input type=file file browser. If you need to restrict it to images or camera input:

    1
    
    <input type="file" accept="image/*" capture="camera" id="image-file" name="image-file" />
    
  2. When the user selects an image, bind a change event to the input file to automatically read the local file.

    1
    2
    3
    4
    5
    6
    7
    
    var image_file = document.getElementById("image-file");
    if (typeof FileReader === 'undefined') {
        image.innerHTML = "Sorry, your browser does not support FileReader";
        image_file.setAttribute('disabled', 'disabled');
    } else {
        image_file.addEventListener('change', readFile, false);
    }
    
  3. image is an img tag with the id image. The readFile function reads the image and automatically center-crops it to a width that adapts to the screen and a fixed height of 180px. The cropping process uses Canvas.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    
    function readFile() {
        var file = this.files[0];
        if (!/image\/\w+/.test(file.type)) {
            alert("The file must be an image!");
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
            var image = document.getElementById("image");
            var img = new Image();
            img.src = this.result;
            img.onload = function() {
                var x = 0, y = 0, width = img.width, height = img.height;
                if (img.width / window.innerWidth > img.height / 180) {
                    width = window.innerWidth * img.height / 180;
                    x = (img.width - width) / 2;
                } else {
                    height = 180 * img.width / window.innerWidth;
                    y = (img.height - height) / 2;
                }
    
                var canvas = document.createElement('canvas');
                canvas.width = window.innerWidth;
                canvas.height = 180;
                var ctx = canvas.getContext('2d');
                ctx.drawImage(img, x, y, width, height, 0, 0, canvas.width, canvas.height);
                var data = canvas.toDataURL();
    
                image.innerHTML = '<img class="img-responsive" style="width:100%; height: 180px;" src="' + data + '" alt="" />';
            }
        }
    }
    

Through these steps, the user can select an image, automatically read the local file, and then center-crop it to a width that adapts to the screen with a fixed height of 180px.