我想知道是否能以某种方式获取url的图像内容并将其转换为base64或blob文件并将其附加到src属性吗?
如果可能的话,我该如何以有角度的方式做到这一点?我试图做这样的事情,它不起作用
const fileReader = new FileReader();
let userAvatar: string;
this.avatarSubject = new BehaviorSubject(this.userService.getAvatar(this.channelId));
this.avatarSubject.subscribe(res => {
userAvatar = res;
const binaryImg = atob(userAvatar);
const length = binaryImg.length;
const buffer = new ArrayBuffer(length);
const uint = new Uint8Array(buffer);
const blob = new Blob([uint], {type: 'image/jpeg'});
fileReader.readAsDataURL(blob);
}).unsubscribe();
答案 0 :(得分:0)
您可以将图片src设置为Base64 dataURI,而不是blob。
如果不违反任何cors政策,您可以将图片检索为斑点,然后将其转换为dataURI。
(async ()=>{
var url = 'https://imgur.com/gallery/rh5O7wN';
var blob = await urlToBlob(url);
var datauri = await blobToDataURI(blob);
document.getElementById('img').src = datauri;
})();
function urlToBlob(url) {
return new Promise(done => {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function() {
if (xhr.status === 200) done(new Blob([xhr.response]));
})
xhr.send();
});
}
function blobToDataURI(blob) {
return new Promise(done => {
var a = new FileReader();
a.onload = e => done(e.target.result);
a.readAsDataURL(blob);
});
}