Hashing an Image in Javascript

江枫思渺然 提交于 2019-12-23 09:48:51

问题


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/



来源:https://stackoverflow.com/questions/15208640/hashing-an-image-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!