Converting Blob/File data to ImageData in javascript?

11,244

If you were to use putImageData() you would have to manually decode and decompress the file your self in order to get a bitmap that you then would convert to a canvas bitmap.

There is luckily no need for that -

The File object you get from the input element can be used as a blob object directly. So all we need to do is to create a temporary Object URL of it so we can use it as an image source.

Create an Image object, set the Object URL as source, when loaded simply draw the image onto the canvas. If you want to keep the image for later use define it outside the handler instead. It's important to revoke the URL to free up memory.

Note that you may need to prefix the URL object in some browser - you can do this to cover that:

window.URL = window.URL || window.webkitURL;

Example code

document.querySelector("input").onchange = function(e) {

  var file = e.target.files[0],                  // reference first file BLOB
      url = URL.createObjectURL(file),           // create an Object URL
      img = new Image();                         // create a temp. image object
    
    img.onload = function() {                    // handle async image loading
      URL.revokeObjectURL(this.src);             // free memory held by Object URL
      c.getContext("2d").drawImage(this, 0, 0);  // draw image onto canvas (lazy methodâ„¢)
    };

    img.src = url;                               // start convertion file to image
};
#c {border: 1px solid #000}
Chose an image: <input type=file><br>
<canvas id=c width=600 height=400></canvas>

To get ImageData you simply call:

var idata = context.getImageData(0, 0, width, height);

after the image has been drawn to the canvas.

Share:
11,244
Ganesh K
Author by

Ganesh K

Updated on June 19, 2022

Comments

  • Ganesh K
    Ganesh K almost 2 years

    I am using file input element to capture an image from android browser. Now I would like to convert the blob data into ImageData so that I can render it on a canvas using putImageData.

    <!DOCTYPE html>
    <html>
    
    <body>
        <input type="file" id="file" />
    </body>
    
    <script>
        function handleFileSelect(evt) {
    
            var files = evt.target.files; // FileList object
    
            var selFile = files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
            var blobData = e.target.result;    
                console.log(e.target.result);
            };
    
            reader.onerror = function(e) {
                console.log(e);
            };
            reader.readAsArrayBuffer(selFile);
        }
    
    
        document.getElementById('file').addEventListener('change',handleFileSelect, false);
    </script>
    
    </html>
    

    In the above code, How can I convert blobData to ImageData? Thanks In advance.