How to get the buffer data of my image in <img>?

I have an image tag in my HTML code with src containing the path to a local image.

<img alt="abc" src="./images/abc.png" />

Upon clicking the image, I want to call a JavaScript method that will return the buffer data of the image.

Example buffer:

(23234)[234,345,786]

How is it done in pure JavaScript?

1 answer

  • answered 2018-01-14 11:22 Isma

    You can try creating a canvas and drawing the image to it, you can get the data in base64 using toDataURL, then just convert the base64 string to a byte array:

    Add an id to identify your image:

    <img id="abc" alt="abc" src="./images/abc.png" />
    

    Then when the image is loaded, you can create a temporary canvas as follows:

    var image = document.getElementById('abc');
    var rawData = null;
    var imageBytes = null;
    
    image.onload = function() {
        var tempCanvas = document.createElement('canvas');
        tempCanvas.width = image.naturalWidth;
        tempCanvas.height = image.naturalHeight;
    
        tempCanvas.getContext('2d').drawImage(image, 0, 0);
    
        //Save raw data in base64
        rawData = tempCanvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
    
        //Convert to byte array
        imageBytes = base64ToArrayBuffer(rawData);
    }
    
    
    function base64ToArrayBuffer(base64) {
        var binary_string =  window.atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array( len );
        for (var i = 0; i < len; i++)        {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }
    

    Here is a fiddle with a working example: https://jsfiddle.net/z2pqtyzb/3/

    The function to convert to a byte array from base64 came from this answer:

    Convert base64 string to ArrayBuffer