問題描述
我正在構(gòu)建一個(gè) Ionic2 應(yīng)用程序.我正在嘗試將圖像 url 轉(zhuǎn)換為 base64 圖像.我找到了我正在嘗試使用的 this.
我有以下代碼:
var imgUrl = 'https://www.google.de/images/srpr/logo11w.png';讓 base64image = this.getBase64Image(imgUrl);控制臺(tái).log(base64image);
和
public getBase64Image(imgUrl) {var img = new Image();img.src = imgUrl;img.setAttribute('crossOrigin', '匿名');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,/, "");}
但是,它會(huì)輸出以下內(nèi)容:
<塊引用>數(shù)據(jù):,
我沒有收到任何錯(cuò)誤,但需要的是 base64 圖像.
我的代碼一定不正確.誰能告訴我如何將 url 轉(zhuǎn)換為 base64 圖像?
謝謝
更新
感謝以下人員的反饋,我已按照他們的建議來加載圖像.現(xiàn)在我有以下代碼:
public getBase64Image(imgUrl): Promise{return new Promise<string>(resolve => {var img = new Image();img.src = imgUrl;img.setAttribute('crossOrigin', '匿名');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);解析(dataURL.replace(/^data:image/(png|jpg);base64,/, ""));});});}
用法:
let promise64: Promise;= this.getBase64Image(personModel.avatar);promise64.then((數(shù)據(jù)) => {personModel.avatar64 = 數(shù)據(jù);});
當(dāng)我運(yùn)行 console.log 時(shí),這似乎確實(shí)創(chuàng)建了一個(gè) base64 圖像.
但是,我確實(shí)收到以下錯(cuò)誤:
<塊引用>錯(cuò)誤:無法在HTMLCanvasElement"上執(zhí)行toDataURL":可能無法導(dǎo)出受污染的畫布.在 HTMLImageElement.img.onload (utilityService.ts:80)
第 80 行:var dataURL = canvas.toDataURL("image/png");
我原以為以下代碼可以解決此安全問題,但無濟(jì)于事:
img.setAttribute('crossOrigin', 'anonymous');
更多信息:
完全錯(cuò)誤:
<代碼>:8100/iVBORw0KGgoAAAANSUhEUgAAAbgAAAG5CAYAAAD8liEWAAAgAElEQVR4Xty9B3NkR5Ksm ... bNkFj80enI0JnJ80 + gTsx2sbrX9zhp7k1oOOPZ5K7Oh/AvN0hP6tzZ6QAAAAAElFTkSuQmCC:1 GET HTTP://本地主機(jī):8100/iVBORw0KGgoAAAANSUhEUgAAAbgAAAG5CAYAAAD8liEWAAAgAElEQ ... t3bNkFj80enI0JnJ80 + gTsx2sbrX9zhp7k1oOOPZ5K7Oh/AvN0hP6tzZ6QAAAAAElFTkSuQmCC凈:: ERR_EMPTY_RESPONSEpolyfills.js:3 POST http://localhost:8080/jbosswildfly-1.0/person/updatetime 400(錯(cuò)誤請(qǐng)求)e@polyfills.js:3t.scheduleTask@polyfills.js:3e.scheduleMacroTask@polyfills.js:3(匿名)@ polyfills.js:3發(fā)送@VM9549:3(匿名)@xhr_backend.js:117Observable.subscribe@Observable.js:45MapOperator.call@map.js:54Observable.subscribe@Observable.js:42(匿名)@personService.ts:141t@polyfills.js:3PersonService.updateTimeStamps@personService.ts:140(匿名)@searchjobsParent.ts:109t.invoke@polyfills.js:3onInvoke@ng_zone.js:236t.invoke@polyfills.js:3onInvoke@ng_zone.js:236t.invoke@polyfills.js:3e.run@polyfills.js:3(匿名)@ polyfills.js:3t.invokeTask@polyfills.js:3onInvokeTask@ng_zone.js:227t.invokeTask@polyfills.js:3onInvokeTask@ng_zone.js:227t.invokeTask@polyfills.js:3e.runTask@polyfills.js:3我@polyfills.js:3polyfills.js:3 GET http://localhost:8080/jbosswildfly-1.0/person/list/favouritejob/null/0/400(錯(cuò)誤請(qǐng)求)例外:無法在HTMLCanvasElement"上執(zhí)行toDataURL":可能無法導(dǎo)出受污染的畫布.ErrorHandler.handleError@error_handler.js:47IonicErrorHandler.handleError @ ionic-error-handler.js:56下一個(gè)@application_ref.js:272schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub@Subscriber.js:223SafeSubscriber.next@Subscriber.js:172訂閱者._next @訂閱者.js:125訂閱者.next@訂閱者.js:89Subject.next@Subject.js:55EventEmitter.emit@async.js:74NgZone.triggerError @ ng_zone.js:278onHandleError @ ng_zone.js:257t.handleError @ polyfills.js:3e.runTask@polyfills.js:3調(diào)用@polyfills.js:3error_handler.js:52 原始堆棧跟蹤:ErrorHandler.handleError@error_handler.js:52IonicErrorHandler.handleError @ ionic-error-handler.js:56下一個(gè)@application_ref.js:272schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub@Subscriber.js:223SafeSubscriber.next@Subscriber.js:172訂閱者._next @訂閱者.js:125訂閱者.next@訂閱者.js:89Subject.next@Subject.js:55EventEmitter.emit@async.js:74NgZone.triggerError @ ng_zone.js:278onHandleError @ ng_zone.js:257t.handleError @ polyfills.js:3e.runTask@polyfills.js:3調(diào)用@polyfills.js:3error_handler.js:53 錯(cuò)誤:無法在HTMLCanvasElement"上執(zhí)行toDataURL":可能無法導(dǎo)出受污染的畫布.在 HTMLImageElement.img.onload (utilityService.ts:82)在 HTMLImageElement.n [as _onload] (polyfills.js:2)在 t.invokeTask (polyfills.js:3)在 Object.onInvokeTask (ng_zone.js:227)在 t.invokeTask (polyfills.js:3)在 e.runTask (polyfills.js:3)在 HTMLImageElement.invoke (polyfills.js:3)
當(dāng)圖像完全加載時(shí),圖像實(shí)例會(huì)觸發(fā) onload
事件.有了這個(gè),另一個(gè)問題是處理異步函數(shù).為了能夠使用 getBase64Image
使用的內(nèi)容,必須使用回調(diào)函數(shù).沒有回調(diào)函數(shù),函數(shù)返回 undefined
讓 base64image = this.getBase64Image(imgUrl);控制臺(tái).log(base64image);//不明確的
調(diào)整功能
public getBase64Image(imgUrl, callback) {var img = new Image();//onload 當(dāng)圖像完全加載時(shí)觸發(fā),并且具有寬度和高度img.onload = 函數(shù)(){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,/, "");回調(diào)(數(shù)據(jù)URL);//base64 字符串};//設(shè)置屬性和srcimg.setAttribute('crossOrigin', '匿名');//img.src = imgUrl;}
用法:
this.getBase64Image(imgUrl, function(base64image){控制臺(tái).log(base64image);});
I am building an Ionic2 app. I am trying to convert an image url to a base64 image. I have found this which I am trying to make use of.
I have the following code:
var imgUrl = 'https://www.google.de/images/srpr/logo11w.png';
let base64image = this.getBase64Image(imgUrl);
console.log(base64image);
and
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,/, "");
}
But, it outputs the following:
data:,
I get no errors, but expect a base64 image.
My code must me incorrect. Can anyone please advise how to convert the url to a base64 image?
Thanks
UPDATE
Thank you to the feedback from the guys below, I have followed their advise to wit for the image to load. Now I have the following code:
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,/, ""));
});
});
}
usage:
let promise64: Promise<string> = this.getBase64Image(personModel.avatar);
promise64.then((data) => {
personModel.avatar64 = data;
});
This does seem to create a base64 image when I run the console.log.
However, I do get the following error:
Error: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. at HTMLImageElement.img.onload (utilityService.ts:80)
Line 80: var dataURL = canvas.toDataURL("image/png");
I would have thought the following code would resolve this security issue, but to no avail:
img.setAttribute('crossOrigin', 'anonymous');
More info:
Full error:
: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)
Image instance fires onload
event when the image is fully loaded. With this, another issue comes in which is dealing asynchronous functions. To be able to use what getBase64Image
uses, a callback function must be used. Without a callback function, the function returns undefined
let base64image = this.getBase64Image(imgUrl);
console.log(base64image); // undefined
Adjusted function
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;
}
Usage:
this.getBase64Image(imgUrl, function(base64image){
console.log(base64image);
});
這篇關(guān)于Javascript 將 URL 轉(zhuǎn)換為 BASE64 圖像的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!