Get image data url in JavaScript?

后端 未结 8 2035
南笙
南笙 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 05:43

    shiv / shim / sham

    If your image(s) are already loaded (or not), this "tool" may come in handy:

    Object.defineProperty
    (
        HTMLImageElement.prototype,'toDataURL',
        {enumerable:false,configurable:false,writable:false,value:function(m,q)
        {
            let c=document.createElement('canvas');
            c.width=this.naturalWidth; c.height=this.naturalHeight;
            c.getContext('2d').drawImage(this,0,0); return c.toDataURL(m,q);
        }}
    );
    

    .. but why?

    This has the advantage of using the "already loaded" image data, so no extra request in needed. Aditionally it lets the end-user (programmer like you) decide the CORS and/or mime-type and quality -OR- you can leave out these arguments/parameters as described in the MDN specification here.

    If you have this JS loaded (prior to when it's needed), then converting to dataURL is as simple as:

    examples

    HTML
    <img src="/yo.jpg" onload="console.log(this.toDataURL('image/jpeg'))">
    
    JS
    console.log(document.getElementById("someImgID").toDataURL());
    

    GPU fingerprinting

    If you are concerned about the "preciseness" of the bits then you can alter this tool to suit your needs as provided by @Kaiido's answer.

    0 讨论(0)
  • 2020-11-21 05:44

    Use onload event to convert image after loading

    function loaded(img) {
      let c = document.createElement('canvas')
      c.getContext('2d').drawImage(img, 0, 0)
      msg.innerText= c.toDataURL();
    }
    pre { word-wrap: break-word; width: 500px; white-space: pre-wrap; }
    <img onload="loaded(this)" src="https://cors-anywhere.herokuapp.com/http://lorempixel.com/200/140" crossorigin="anonymous"/>
    
    <pre id="msg"></pre>

    0 讨论(0)
  • 2020-11-21 05:47

    This is all you need to read.

    https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString

    var height = 200;
    var width  = 200;
    
    canvas.width  = width;
    canvas.height = height;
    
    var ctx = canvas.getContext('2d');
    
    ctx.strokeStyle = '#090';
    ctx.beginPath();
    ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2);
    ctx.stroke();
    
    canvas.toBlob(function (blob) {
      //consider blob is your file object
    
      var reader = new FileReader();
    
      reader.onload = function () {
        console.log(reader.result);
      }
    
      reader.readAsBinaryString(blob);
    });
    
    0 讨论(0)
  • 2020-11-21 05:47

    In HTML5 better use this:

    {
    //...
    canvas.width = img.naturalWidth; //img.width;
    canvas.height = img.naturalHeight; //img.height;
    //...
    }
    
    0 讨论(0)
  • 2020-11-21 05:52

    A more modern version of kaiido's answer using fetch would be:

    function toObjectUrl(url) {
      return fetch(url)
          .then((response)=> {
            return response.blob();
          })
          .then(blob=> {
            return URL.createObjectURL(blob);
          });
    }
    

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    Edit: As pointed out in the comments this will return an object url which points to a file in your local system instead of an actual DataURL so depending on your use case this might not be what you need.

    You can look at the following answer to use fetch and an actual dataURL: https://stackoverflow.com/a/50463054/599602

    0 讨论(0)
  • 2020-11-21 05:54

    This Function takes the URL then returns the image BASE64

    function getBase64FromImageUrl(url) {
        var img = new Image();
    
        img.setAttribute('crossOrigin', 'anonymous');
    
        img.onload = function () {
            var canvas = document.createElement("canvas");
            canvas.width =this.width;
            canvas.height =this.height;
    
            var ctx = canvas.getContext("2d");
            ctx.drawImage(this, 0, 0);
    
            var dataURL = canvas.toDataURL("image/png");
    
            alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
        };
    
        img.src = url;
    }
    

    Call it like this : getBase64FromImageUrl("images/slbltxt.png")

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