Hashing an Image in Javascript

2019-06-21 21:16发布

问题:

I have currently been trying to hash an image from my browser using javascript. However, I've been hashing a string of the dataURL or the pixel data that I've been retrieving from the canvas element in HTML. This is obviously not the same as hashing the raw data of the image which is what I would like to do.

For example the data that would be used for the same image in the php hash file function.

Does anybody know how I can access this raw image data using javascript to get a hash value that would be equivalent to the result hash I get from PHP hash_file($file)?

Thanks!

回答1:

You can get the raw data of an image with an XHR request to that image file location.

var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/file.png', true);
xhr.responseType = 'arraybuffer'; // this will accept the response as an ArrayBuffer
xhr.onload = function(buffer) {
    var words = new Uint32Array(buffer),
        hex = '';
    for (var i = 0; i < words.length; i++) {
      hex += words.get(i).toString(16);  // this will convert it to a 4byte hex string
    }
    console.log(hex);
};
xhr.send();

After that, you can use whatever hashing algorithm you'd like. Here's a library of them: https://code.google.com/p/crypto-js/