Get image data url in JavaScript?

后端 未结 8 2044
南笙
南笙 2020-11-21 05:11

I have a regular HTML page with some images (just regular HTML tags). I\'d like to get their content, base64 encoded preferably, without the need

8条回答
  •  执念已碎
    2020-11-21 06:02

    Coming long after, but none of the answers here are entirely correct.

    When drawn on a canvas, the passed image is uncompressed + all pre-multiplied.
    When exported, its uncompressed or recompressed with a different algorithm, and un-multiplied.

    All browsers and devices will have different rounding errors happening in this process
    (see Canvas fingerprinting).

    So if one wants a base64 version of an image file, they have to request it again (most of the time it will come from cache) but this time as a Blob.

    Then you can use a FileReader to read it either as an ArrayBuffer, or as a dataURL.

    function toDataURL(url, callback){
        var xhr = new XMLHttpRequest();
        xhr.open('get', url);
        xhr.responseType = 'blob';
        xhr.onload = function(){
          var fr = new FileReader();
        
          fr.onload = function(){
            callback(this.result);
          };
        
          fr.readAsDataURL(xhr.response); // async call
        };
        
        xhr.send();
    }
    
    toDataURL(myImage.src, function(dataURL){
      result.src = dataURL;
    
      // now just to show that passing to a canvas doesn't hold the same results
      var canvas = document.createElement('canvas');
      canvas.width = myImage.naturalWidth;
      canvas.height = myImage.naturalHeight;
      canvas.getContext('2d').drawImage(myImage, 0,0);
    
      console.log(canvas.toDataURL() === dataURL); // false - not same data
      });
    
    

提交回复
热议问题