Get image data url in JavaScript?

后端 未结 8 2046
南笙
南笙 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条回答
  •  -上瘾入骨i
    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")

提交回复
热议问题