[英]Typescript - Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported
I am building an Ionic App and I am getting this error when I try to convert to base64 an image from an URL. 我正在构建一个Ionic应用程序,当我尝试从URL转换为base64图像时出现此错误。
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
My code is the following: 我的代码如下:
public getBase64Image(imgUrl: string): Promise<string> {
if (!imgUrl.includes("http")) {
return;
}
return new Promise<string>(resolve => {
let img = new Image();
img.src = imgUrl;
img.crossOrigin = "anonymous"
img.onload = (() => {
let canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
let dataURL = canvas.toDataURL("image/png");
resolve(dataURL);
});
});
}
I've read other questions where setting anonymous
in crossOrigin
was the solution, but I already have it. 我读过其他问题,在
crossOrigin
中设置anonymous
是解决方案,但我已经有了。
Hope you can help me, thanks. 希望你能帮助我,谢谢。
EDIT 1 编辑1
As a note, I don't get this the first time that I convert an image to base64 but I get it in the following times I try to edit an image. 请注意,我不是第一次将图像转换为base64时得到此信息,但是在接下来的几次尝试编辑图像时得到了它。
Instead of the approach in the first post, I've switched to downloading the image using Angular's HttpClient and then getting its base64. 代替第一篇文章中的方法,我切换到使用Angular的HttpClient下载图像,然后获取其base64。
Code: 码:
public getBase64Image(imgUrl: string): Observable<string> {
return new Observable(observer => {
this.http.get(imgUrl, { responseType: 'blob' }).subscribe(data => {
var reader = new FileReader();
reader.readAsDataURL(data);
reader.onloadend = () => {
observer.next(reader.result.toString().replace(":application/octet-stream;", ":image/png;"));
observer.complete();
}
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.