how get image hash in the browser in javascript

To get the hash of an image in the browser using JavaScript, you can use the canvas element. The process involves creating a new canvas, loading the image onto the canvas, and then extracting the pixel data. The pixel data can then be hashed using a cryptographic algorithm like SHA-256.

Here's a sample code that demonstrates this process:

index.tsx
function getImageHash(url, callback) {
  var img = new Image();
  img.crossOrigin = "Anonymous";
  img.src = url;
  img.onload = function() {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var data = imageData.data;

    var hash = crypto.subtle.digest("SHA-256", data.buffer)
      .then(function(hash){ callback(convertBufferToHex(hash)); });

    function convertBufferToHex(buffer) {
      var hexString = '';
      var byteArray = new Uint8Array(buffer);
      byteArray.forEach(function(byte) {
        hexString += ('0' + byte.toString(16)).slice(-2);
      });
      return hexString;
    }
  }
}
819 chars
29 lines

This function takes in the URL of the image you want to hash and a callback function that will be executed when the hash is calculated. The getImageHash function creates an image element, sets the crossOrigin property to "Anonymous" to avoid CORS issues, and sets the source URL to the specified image. When the image is loaded, it creates a new canvas and draws the image onto it. It then retrieves the pixel data from the canvas and generates a hash using the crypto.subtle.digest method with the SHA-256 algorithm. Finally, it converts the hash buffer to a hexadecimal string and calls the callback function with the result.

gistlibby LogSnag