从资产获取图像并将其转换为base64

时间:2019-06-20 13:15:02

标签: angular

我正在尝试制作一个包含图像的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;
  };
}

是否有一种方法可以从该路径获取图像,以某种方式将其制成文件,然后进行转换?还是我应该使用另一种方式/对象格式(而不是文件)来做到这一点?

1 个答案:

答案 0 :(得分:2)

只需使用let data = { 'type': 'FeatureCollection', 'features': [{ 'type': 'Feature', 'properties': { 'color': 'red' }, 'geometry': { 'type': 'Polygon', 'coordinates': [ [ [ 115.813867, -31.932177 ], [ 115.813867, -31.932177 ], [ 115.813867, -31.932087 ], [ 115.813962, -31.932087 ], [ 115.813962, -31.932124 ], [ 115.814005, -31.932124 ], [ 115.814005, -31.932168 ], [ 115.813962, -31.932168 ], [ 115.813962, -31.932177 ], [ 115.813867, -31.932177 ] ] ] } }, { 'type': 'Feature', 'properties': { 'color': 'blue' }, 'geometry': { 'type': 'Polygon', 'coordinates': [ [ [ 115.813962, -31.932087 ], [ 115.813894, -31.932087 ], [ 115.813894, -31.932042 ], [ 115.81391, -31.932042 ], [ 115.81391, -31.931967 ], [ 115.813984, -31.931967 ], [ 115.813984, -31.932042 ], [ 115.81401, -31.932042 ], [ 115.81401, -31.932087 ], [ 115.813962, -31.932087 ] ] ] } }, { 'type': 'Feature', 'properties': { 'color': 'green' }, 'geometry': { 'type': 'Polygon', 'coordinates': [ [ [ 115.81391, -31.931967 ], [ 115.81391, -31.931931 ], [ 115.813849, -31.931931 ], [ 115.813849, -31.9319 ], [ 115.81386, -31.9319 ], [ 115.81386, -31.931868 ], [ 115.813984, -31.931868 ], [ 115.813984, -31.931967 ], [ 115.81391, -31.931967 ] ] ] } }] }; map.on('load', function () { map.addLayer({ 'id': 'maine', 'type': 'fill', 'source': { 'type': 'geojson', 'data': data }, 'layout': {}, 'paint': { 'fill-color': ['get', 'color'], 'fill-opacity': 0.8 } }); }); 调用HttpClient的{​​{1}}方法。这将导致响应被读取为get对象。

然后您可以使用{ responseType: 'blob' }进行读取并将其转换为base64。

尝试一下:

blob

  

这是您推荐的Working Sample StackBlitz