简体   繁体   English

从网址读取图片,并将其保存在html / phonegap中的base64中

[英]Read image from Url and save it in base64 in html / phonegap

I'm trying to read a URL (the resource of which is an image) and encode this image in base64 to save it in a database. 我正在尝试读取URL(其资源是图像)并在base64中对该图像进行编码以将其保存在数据库中。

I've looked around Google and Stackoverflow and a lot of people say that it is impossible to save a base64 formatted image that you read from a URL.(Are they wrong?) 我到处都是Google和Stackoverflow,很多人说保存从URL读取的base64格式的图像是不可能的(他们错了吗?)

My steps are as follows: 我的步骤如下:

I parse an XML file where there is a URL for the image. 我解析一个XML文件,其中有图像的URL。 I'm trying to save this image in a base64 format in a DB. 我试图将此图像以base64格式保存在数据库中。

Can anybody help me? 有谁能够帮助我?

I can't readily put together an example of this, but it should be possible, assuming the image is coming from the same domain you are running the code on, or you can control the cross origin header for the image (or else you'll get a Cross-origin error). 我无法轻易将其示例放在一起,但是应该可以,假设图像来自您正在运行代码的同一域,或者您可以控制图像的跨原点标头(否则您可以会得到跨域错误)。

Assuming this is the case, you can. 假设是这种情况,您可以。 Here is a JSFiddle where I encode the logo of JSFiddle: http://fiddle.jshell.net/5S6BY/ (since that logo is on the same domain as where the code is running, it works). 这是我在其中编码JSFiddle徽标的JSFiddle: http ://fiddle.jshell.net/5S6BY/(因为徽标与代码运行所在的域位于同一域中,所以它可以工作)。

The trick is to draw it to a canvas, then convert that canvas to a base64. 诀窍是将其绘制到画布上,然后将该画布转换为base64。

Here is the code: 这是代码:

var url = "http://fiddle.jshell.net/img/logo.png";
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var ctx = canvas.getContext('2d');

var image = new Image();
image.crossOrigin = 'anonymous';
image.addEventListener('load', function() {
    ctx.drawImage(image, 0, 0, image.width, image.height);
    document.body.innerHTML = canvas.toDataURL();
});
image.src = url;

It's pretty straight forward. 非常简单。 Load the image, draw the image to the canvas, then call canvas.toDataUrl() to get the base64 encoded version, which you can use to do whatever you want. 加载图像,将图像绘制到画布上,然后调用canvas.toDataUrl()获得base64编码的版本,您可以使用该版本进行任何所需的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM