javascript 如何使用javascript将图像url转换为dataurl(base64数据)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18894472/
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-10-27 13:36:20  来源:igfitidea点击:

how to convert image url to dataurl (base64 data) with javascript

javascriptjqueryhtmlcanvashtml5-canvas

提问by atluriajith

how to convert image url to base64 encoded data url without using html5 canvas object.

如何在不使用 html5 canvas 对象的情况下将图像 url 转换为 base64 编码的数据 url。

canvas.todataURL()

I am gettting base64 data using canvas.todataURL, but it fails to read remote url's, so I want to convert my image url to dataurl with out using canvas.todataURL() and use it in my application.

HOw can I to do this.

我正在使用 canvas.todataURL 获取 base64 数据,但它无法读取远程 url,所以我想将我的图像 url 转换为 dataurl 而不使用 canvas.todataURL() 并在我的应用程序中使用它。

我怎么能做到这一点。

回答by Mandeep Singh

You can use this code-

您可以使用此代码-

HTML-

HTML-

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

javascript-

javascript-

    <script>
     var c = document.getElementById("myCanvas");
     var ctx = c.getContext("2d");
     var img = document.getElementById("preview");
     ctx.drawImage(img, 10, 10);
     alert(c.toDataURL());
    </script>

found it here- How to get base64 encoded data from html image

在这里找到 - 如何从 html 图像中获取 base64 编码数据

回答by Strille

You can't do it purely in javascript without using canvas.toDataUrl(). You would have to do something server-side. Basically create a simple service which takes an url to an image as parameter and then returns that image as a base64 string.

如果不使用 canvas.toDataUrl(),就不能完全在 javascript 中完成。您将不得不在服务器端做一些事情。基本上创建一个简单的服务,它将图像的 url 作为参数,然后将该图像作为 base64 字符串返回。