Get image data url in JavaScript?

后端 未结 8 2092
南笙
南笙 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
    
    
    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.

提交回复
热议问题