How to get base64 encoded data from html image

前端 未结 2 1973
南旧
南旧 2020-12-02 15:45

I have a registration form where users can choose an avatar. They have 2 possibilities:

  1. Choose a default avatar
  2. Upload their own avatar

相关标签:
2条回答
  • 2020-12-02 16:04

    You can try following sample http://jsfiddle.net/xKJB8/3/

    <img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
    <canvas id="myCanvas" />
    

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("preview");
    ctx.drawImage(img, 10, 10);
    alert(c.toDataURL());
    
    0 讨论(0)
  • 2020-12-02 16:05

    You can also use the FileReader class :

        var reader = new FileReader();
        reader.onload = function (e) {
            var data = this.result;
        }
        reader.readAsDataURL( file );
    
    0 讨论(0)
提交回复
热议问题