Last Updated: March 28, 2018
·
28.09K
· DTasev

Loading image from local file into JavaScript and getting pixel data

Inside the <body>:

<input type="file" id="myFile">Load image</input>
<br>
<img id="myImage" style="border:1px" />

Very simple markup, just for demonstration purposes.

When the file is selected, the onchange event triggers. We use that to load the file from the file system.

When the file is loaded, the onload event triggers, the () => showImage(fr) captures the file reader fr reference, so that it can be passed as a parameter.

showImage sets the source in the image tag, telling the browser to load the image. The onload event captures the image element reference, finally extracting the image data and storing it in the imageData variable for further processing.

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var imageData;
document.getElementById('myFile').onchange = function (evt) {
    var tgt = evt.target || window.event.srcElement,
        files = tgt.files;

    // FileReader support
    if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = () => showImage(fr);
        fr.readAsDataURL(files[0]);
    }
}

function showImage(fileReader) {
    var img = document.getElementById("myImage");
    img.onload = () => getImageData(img);
    img.src = fileReader.result;
}

function getImageData(img) {
    ctx.drawImage(img, 0, 0);
    imageData = ctx.getImageData(0, 0, img.width, img.height).data;
    console.log("image data:", imageData);
}