Get image data url in JavaScript?

后端 未结 8 2071
南笙
南笙 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:01

    Note: This only works if the image is from the same domain as the page, or has the crossOrigin="anonymous" attribute and the server supports CORS. It's also not going to give you the original file, but a re-encoded version. If you need the result to be identical to the original, see Kaiido's answer.


    You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.

    It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.

    function getBase64Image(img) {
        // Create an empty canvas element
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
    
        // Copy the image contents to the canvas
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
    
        // Get the data-URL formatted image
        // Firefox supports PNG and JPEG. You could check img.src to
        // guess the original format, but be aware the using "image/jpg"
        // will re-encode the image.
        var dataURL = canvas.toDataURL("image/png");
    
        return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    }
    

    Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".

    0 讨论(0)
  • 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
      });
    <img id="myImage" src="https://dl.dropboxusercontent.com/s/4e90e48s5vtmfbd/aaa.png" crossOrigin="anonymous">
    <img id="result">

    0 讨论(0)
提交回复
热议问题