我正在尝试制作一个包含图像的pdf,但在实际获取代码中的图像时遇到了困难。在我的项目资产文件夹中,有一个图像列表(svg 和 png),我想要获取这些图像并将其转换为 base64,以便我可以将它们用于我的 pdf。
问题是我找不到一种方法来实际加载我知道它存在于该资产文件夹中的图像,例如使用绝对路径(/assets/images/{imagename}.png),并将其加载到内部代码
这是我用于转换为 base64 的代码:
convertImageToBase64(file: File) {
const reader: FileReader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (): string => {
const base64String: string = (reader.result as string).match(/.+;base64,(.+)/)[1];
return base64String;
};
}
有没有办法从该路径获取图像,使其成为文件,然后将其转换?或者我应该使用另一种方式/对象格式来执行此操作(而不是文件)?
只需致电HttpClient
's get
方法与{ responseType: 'blob' }
。这将导致响应被读取为blob
Object.
然后你可以使用FileReader
读取它并将其转换为 Base64。
尝试一下:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
constructor(private http: HttpClient) {}
ngOnInit() {
this.http.get('/assets/image.jpg', { responseType: 'blob' })
.subscribe(res => {
const reader = new FileReader();
reader.onloadend = () => {
var base64data = reader.result;
console.log(base64data);
}
reader.readAsDataURL(res);
console.log(res);
});
}
}
这是一个工作示例 StackBlitz https://stackblitz.com/edit/angular-read-file-as-blob?file=src/app/app.component.ts供您参考。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)