Javascript将URL转换为BASE64映像



我正在构建一个Ionic2应用程序。我正在尝试将图像url转换为base64图像。我发现了这个,我正试图利用它。

我有以下代码:

var imgUrl = 'https://www.google.de/images/srpr/logo11w.png';
let base64image = this.getBase64Image(imgUrl);
console.log(base64image);

public getBase64Image(imgUrl) {
var img = new Image();
img.src = imgUrl;
img.setAttribute('crossOrigin', 'anonymous');
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image/(png|jpg);base64,/, "");
}

但是,它输出以下内容:

数据:,

我没有得到任何错误,但需要一个base64映像。

我的代码一定是错误的。有人能建议如何将url转换为base64图像吗?

感谢

更新

感谢下面的人的反馈,我听从了他们的建议,以便加载图像。现在我有以下代码:

public getBase64Image(imgUrl): Promise<string> {
return new Promise<string>(resolve => {
var img = new Image();
img.src = imgUrl;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = (() => {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
//console.log('UgetBase64Image.dataURL ', dataURL);
resolve(dataURL.replace(/^data:image/(png|jpg);base64,/, ""));
});
});
}

用法:

let promise64: Promise<string> = this.getBase64Image(personModel.avatar);
promise64.then((data) => {
personModel.avatar64 = data;
});

当我运行console.log.时,这似乎确实创建了一个base64映像

然而,我确实得到了以下错误:

Error: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
at HTMLImageElement.img.onload (utilityService.ts:80)

第80行:var dataURL = canvas.toDataURL("image/png");

我本以为以下代码可以解决这个安全问题,但无济于事:

img.setAttribute('crossOrigin', 'anonymous');

更多信息:

完全错误:

:8100/iVBORw0KGgoAAAANSUhEUgAAAbgAAAG5CAYAAAD8liEWAAAgAElEQVR4Xty9B3NkR5Ksm…bNkFj80enI0JnJ80+gTsx2sbrX9zhp7k1oOOPZ5K7Oh/AvN0hP6tzZ6QAAAAAElFTkSuQmCC:1 GET http://localhost:8100/iVBORw0KGgoAAAANSUhEUgAAAbgAAAG5CAYAAAD8liEWAAAgAElEQ…t3bNkFj80enI0JnJ80+gTsx2sbrX9zhp7k1oOOPZ5K7Oh/AvN0hP6tzZ6QAAAAAElFTkSuQmCC net::ERR_EMPTY_RESPONSE
polyfills.js:3 POST http://localhost:8080/jbosswildfly-1.0/person/updatetime 400 (Bad Request)
e @ polyfills.js:3
t.scheduleTask @ polyfills.js:3
e.scheduleMacroTask @ polyfills.js:3
(anonymous) @ polyfills.js:3
send @ VM9549:3
(anonymous) @ xhr_backend.js:117
Observable.subscribe @ Observable.js:45
MapOperator.call @ map.js:54
Observable.subscribe @ Observable.js:42
(anonymous) @ personService.ts:141
t @ polyfills.js:3
PersonService.updateTimeStamps @ personService.ts:140
(anonymous) @ searchjobsParent.ts:109
t.invoke @ polyfills.js:3
onInvoke @ ng_zone.js:236
t.invoke @ polyfills.js:3
onInvoke @ ng_zone.js:236
t.invoke @ polyfills.js:3
e.run @ polyfills.js:3
(anonymous) @ polyfills.js:3
t.invokeTask @ polyfills.js:3
onInvokeTask @ ng_zone.js:227
t.invokeTask @ polyfills.js:3
onInvokeTask @ ng_zone.js:227
t.invokeTask @ polyfills.js:3
e.runTask @ polyfills.js:3
i @ polyfills.js:3
polyfills.js:3 GET http://localhost:8080/jbosswildfly-1.0/person/list/favouritejob/null/0/ 400 (Bad Request)
EXCEPTION: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
ErrorHandler.handleError @ error_handler.js:47
IonicErrorHandler.handleError @ ionic-error-handler.js:56
next @ application_ref.js:272
schedulerFn @ async.js:82
SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ async.js:74
NgZone.triggerError @ ng_zone.js:278
onHandleError @ ng_zone.js:257
t.handleError @ polyfills.js:3
e.runTask @ polyfills.js:3
invoke @ polyfills.js:3
error_handler.js:52 ORIGINAL STACKTRACE:
ErrorHandler.handleError @ error_handler.js:52
IonicErrorHandler.handleError @ ionic-error-handler.js:56
next @ application_ref.js:272
schedulerFn @ async.js:82
SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ async.js:74
NgZone.triggerError @ ng_zone.js:278
onHandleError @ ng_zone.js:257
t.handleError @ polyfills.js:3
e.runTask @ polyfills.js:3
invoke @ polyfills.js:3
error_handler.js:53 Error: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
at HTMLImageElement.img.onload (utilityService.ts:82)
at HTMLImageElement.n [as _onload] (polyfills.js:2)
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (ng_zone.js:227)
at t.invokeTask (polyfills.js:3)
at e.runTask (polyfills.js:3)
at HTMLImageElement.invoke (polyfills.js:3)

映像实例在映像完全加载时触发onload事件。随之而来的另一个问题是处理异步函数。为了能够使用getBase64Image所使用的功能,必须使用回调函数。如果没有回调函数,函数将返回undefined

let base64image = this.getBase64Image(imgUrl);
console.log(base64image); // undefined

调整后的功能

public getBase64Image(imgUrl, callback) {
var img = new Image();
// onload fires when the image is fully loadded, and has width and height
img.onload = function(){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png"),
dataURL = dataURL.replace(/^data:image/(png|jpg);base64,/, "");
callback(dataURL); // the base64 string
};
// set attributes and src 
img.setAttribute('crossOrigin', 'anonymous'); //
img.src = imgUrl;
}

用法:

this.getBase64Image(imgUrl, function(base64image){
console.log(base64image);
});

要在画布上使用来自另一个来源(服务器)的图像,必须为图像提供CORS标头。MDN上的这个页面对此进行了解释。

var imgUrl = 'https://www.google.de/images/srpr/logo11w.png';
var imgUrl = 'https://dl.dropboxusercontent.com/u/139992952/coffee.png';
let base64image = getBase64Image(imgUrl).then(function(base64image) {
console.log(base64image);
}, function(reason) {
console.log(reason); // Error!
});
function getBase64Image(imgUrl) {
return new Promise(
function(resolve, reject) {
var img = new Image();
img.src = imgUrl;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
resolve(dataURL.replace(/^data:image/(png|jpg);base64,/, ""));
}
img.onerror = function() {
reject("The image could not be loaded.");
}
});
}

相关内容

  • 没有找到相关文章

最新更新