Html 如何从html图像中获取base64编码数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15760764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:06:12  来源:igfitidea点击:

How to get base64 encoded data from html image

javascripthtmlimagebase64

提问by Jonas Anseeuw

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
  1. 选择默认头像
  2. 上传自己的头像

In my HTML page I have this.

在我的 HTML 页面中,我有这个。

<img id="preview" src="img/default_1.png">

It displays the chosen avatar. I use the File Api to let users upload their own image. That makes the src of the HTML image to something like this.

它显示所选的头像。我使用 File Api 让用户上传他们自己的图像。这使得 HTML 图像的 src 变成这样。

<img id="preview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA... />

When they post the registration form. The data will be sent to a REST service. I can send the base64 encoded data when a user uploaded an avatar himself. But how do I handle the default avatar? It is an url instead of base64 encoded data.

当他们发布注册表时。数据将被发送到 REST 服务。当用户自己上传头像时,我可以发送 base64 编码的数据。但是我如何处理默认头像?它是一个 url 而不是 base64 编码的数据。

回答by Chamika Sandamal

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

您可以尝试以下示例 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());

回答by httpete

You can also use the FileReader class :

您还可以使用 FileReader 类:

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );