[英]Can i apoint the src img attribute to a blob file or a base64 encoded image?
I was wonder if somehow i could get the image content of a url and transform it into a base64 or a blob file and append it to the src attribute ? 我想知道是否能以某种方式获取url的图像内容并将其转换为base64或blob文件并将其附加到src属性?
And if this is possible how can i do this in the angular way ? 如果可能的话,我该怎么做呢? I tried to do something like this and its not working
我试图做这样的事情,它不起作用
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();
You can set an image src to a Base64 dataURI, not to a blob though. 您可以将图片src设置为Base64 dataURI,而不是blob。
You can retrieve the image as a blob, then convert it to a dataURI, if it doesn't violate any cors policy. 您可以将图片检索为Blob,然后将其转换为dataURI(如果它不违反任何cors策略)。
(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);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.