如何将 blob 图像转换为 base64? base64 变量显示为空
Posted
技术标签:
【中文标题】如何将 blob 图像转换为 base64? base64 变量显示为空【英文标题】:how to convert blob image to base64? base64 variable showing up as null 【发布时间】:2021-09-22 21:18:12 【问题描述】:我正在尝试构建一个用户界面,如果按下按钮,则会发出获取请求并显示图像。但是,当尝试将图像 blob 转换为 base64 时,base64 显示为 null,我不知道为什么。下面是我的组件:
@Component(
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
)
export class HomeComponent implements OnInit
data:any
image:any
retrievedImage: any;
base64Data: any;
retrieveResonse: any;
imageName:any;
constructor(private imageData:imageService,
private httpClient:HttpClient)
ngOnInit(): void
console.log(this.image)
this.imageData.getImages().subscribe((results)=>
console.log(results)
this.data = results
)
getImage2()
var reader = new FileReader();
//Make a call to Spring Boot to get the Image Bytes.
this.httpClient.get('http://localhost:8080/get/' + this.imageName,
responseType:'blob')
.subscribe(
res =>
this.retrieveResonse = res; //this is blob i think
reader.readAsDataURL(this.retrieveResonse)
this.base64Data = reader.result;
//this.base64Data = this.retrieveResonse.picByte;
this.retrievedImage = 'data:image/jpeg;base64,' + this.base64Data;
console.log(this.retrieveResonse)
console.log(this.base64Data)
console.log(this.retrievedImage)
);
下面是我的 HTML 文件:
<p>
<mat-toolbar>
<span>Image Repository</span>
</mat-toolbar>
</p>
<button mat-button style="position:relative; left: 5px; top:2px" (click)="getImage2()">Get an image </button>
<input #image type="text" style="position:relative;left:10px; top: 2.99px" [(ngModel)]="imageName">
<!-- <img *ngIf="image" style="position:relative;top:200px" [src]="image" >
-->
<div class="container row">
<div class="col-md-12">
<div *ngIf=retrievedImage>
<img [src]="retrievedImage" style="position:relative;top:200px" >
</div>
</div>
</div>
为什么在调用getimage2方法时,在控制台登录时this.base64Data
变量显示为null?我会假设使用此代码将 blob 转换为 base64?
【问题讨论】:
【参考方案1】:下载图片的一种可能方式
使用通用的get
下载器:
private download(url: string, params: any): Observable<any>
return this.http.get(url,
reportProgress: true,
observe: 'events',
responseType: 'blob'
);
从以下位置调用它:
onDownloadImage(): void
this.progress = 0;
this.download(this.imageUrl, ).subscribe((event: any) =>
if (event.type === HttpEventType.DownloadProgress)
this.progress = Math.round((100 * event.loaded) / event.total);
console.log('progress', event.loaded);
else if (event instanceof HttpResponse)
this.processReceivedBlob(event.body);
);
下载完成后处理
private processReceivedBlob(blob: any)
var reader = new FileReader();
reader.onload = () =>
const dataUrl: any = reader.result;
const base64 = dataUrl.split(',')[1];
this.img.src = 'data:image/png;base64, ' + base64;
;
reader.readAsDataURL(blob);
在 html 中:
<img [src]="img.src">
工作Stackblitz
【讨论】:
以上是关于如何将 blob 图像转换为 base64? base64 变量显示为空的主要内容,如果未能解决你的问题,请参考以下文章
如何下载 Block Blob (Base64) 文件并使用 Azure Blob 存储将其转换为 PNG?