将Blob转换为图像URL,并在image src中使用以显示图像 [英] Convert Blob to image url and use in image src to display image

查看:1398
本文介绍了将Blob转换为图像URL,并在image src中使用以显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将blob转换为base64/image?
我正在通过API调用获取此Blob,并且尝试在
图像.我已经尝试过stackoverflow答案,但没有任何帮助
我只是试过这个.

How to convert blob to base64/image?
I am getting this blob through API call and I am trying to display it in a
image. I have tried with stackoverflow answers but nothing could help so
I just tried this.

//Angular 5 code  
imageSrc;//global variable  
data = [{"image_blob":{"type":"img/jpg","data":[123,125]}}];//from api  
var blob1 = new Blob([new Uint8Array(data[0].image_blob.data)]);  
const imageUrl = URL.createObjectURL(blob1);  
console.log(imageUrl);//blob:http://localhost:8100/c489.etc  
this.imageSrc = imageUrl;  

<!-- html code -->  
<img [src]='imageSrc' alt="image">  

什么都错过了.请建议

推荐答案

生成base64字符串:

Generate the base64 string:

var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
   base64data = reader.result;     
}

一旦有了它,就可以使用Angular消毒器生成要放入图像 src 中的字符串.示例:

Once you have it, generate the string you'll put in you image src with Angular sanitizer. Example:

import { DomSanitizer } from '@angular/platform-browser';
constructor( ... private sanitizer : DomSanitizer ...){}

public myFunction() : void {
    let mySrc = this.sanitizer.bypassSecurityTrustUrl('data:image/png;base64,' + base64data);
}

您可以根据需要修改类型'data:image/png; base64'.

You can modify the type 'data:image/png;base64,' as you need.

最后,将其放在您的图像中

And to finish, put this in your image:

<img [src]="mySrc" />

这篇关于将Blob转换为图像URL,并在image src中使用以显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆