在Javascript中哈希图像 [英] Hashing an Image in Javascript

查看:256
本文介绍了在Javascript中哈希图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前一直在试图使用JavaScript来从我的浏览器中散列图像。不过,我一直在哈希从HTML中的canvas元素检索的dataURL或像素数据的字符串。这显然不同于哈希图像的原始数据,这是我想要做的。



例如用于php hash文件函数中相同图像的数据。



任何人都知道我如何使用JavaScript访问这个原始图像数据来获得一个散列值,它将等于我从PHP hash_file($ file)获得的结果散列值?

感谢!

解决方案

您可以通过XHR请求获取图像的原始数据到该图像文件位置。

  var xhr = new XMLHttpRequest(); 
xhr.open('GET','/my/image/file.png',true);
xhr.responseType ='arraybuffer'; //这将接受ArrayBuffer的响应
xhr.onload = function(buffer){
var words = new Uint32Array(buffer),
hex ='';
for(var i = 0; i hex + = words.get(i).toString(16); //这会将它转换为一个4字节的十六进制字符串
}
console.log(hex);
};
xhr.send();

之后,您可以使用任何您想要的散列算法。以下是其中的一个库: https://code.google.com/p/crypto-js/


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!

解决方案

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/

这篇关于在Javascript中哈希图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆