【问题标题】:How can I display image encoded in base64 format in Angular 6?如何在 Angular 6 中显示以 base64 格式编码的图像?
【发布时间】:2019-06-27 06:27:51
【问题描述】:

我遇到了一个与 Angular 6 相关的问题,以及显示以 base64 格式编码的图像。任何想法为什么下面显示的代码不显示图像?

html:

<tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
<img src="{{this.hello}}" />

ts:

this.hello = "data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."

虽然下面显示的代码可以正常工作并显示图片?

html:

<tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
<!--<img src="data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."/>

this.hello 在构造函数中分配只是为了测试目的。我以这种方式创建它this.hello = 'data:image/png;base64, ' + this.UploaderService.imageRecognitionRowsData[0].toString() 我的主要目标是在这个循环&lt;tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows"&gt; 中显示imageRecognitionRowsData。因此,对于第一次迭代,我将显示图像imageRecognitionRowsData[0],然后在下一次迭代中显示图像imageRecognitionRowsData[1] 等。this.UploaderService.tableImageRecognition.dataRows 的长度始终与this.UploaderService.imageRecognitionRowsData 相同当我添加&lt;p&gt;{{this.hello}}&lt;/p&gt; 时,我在html 中得到相同的字符串。 我不知道出了什么问题。我也尝试了this.hello2 = this.sanitizer.bypassSecurityTrustResourceUrl(this.hello);this.hello2 = this.sanitizer.bypassSecurityTrustUrl(this.hello);&lt;img [src]="this.hello" /&gt; 等,但没有任何效果。任何想法如何解决这个问题?

【问题讨论】:

    标签: html angular typescript base64 angular6


    【解决方案1】:

    您不会在 Angular 的 html 模板中使用 this。默认情况下,所有变量/成员方法都在类上解析。直接访问变量如下:

    <img [src]="hello" />
    

    【讨论】:

    • 图片还是没有显示出来。
    • 肯定还有其他问题。调试你的逻辑。
    • 我收到 Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:4200/hello 但我确信我不会向 http://localhost:4200/hello 发送请求。有什么想法吗?
    【解决方案2】:

    您不要使用“this”来引用组件“ts”文件中定义的变量。删除“this”可能会解决您的问题。

    请查看此 stackbliz Fiddle。查看应用组件内部以查看实现。

    StackBlitz

    【讨论】:

    • 我收到警告 WARNING: sanitizing unsafe URL value data:image/png;base64, /9j/4AAQSkZJRgABAQAAA 和错误 Failed to load resource: unsupported URL
    • 是的,这是一个浏览器安全警告,请点击此链接解决问题stackoverflow.com/questions/38593515/…
    • 我尝试了一切 - 将其显示为string,作为SafeResourceUrl 变量,我尝试使用bypassSecurityTrustUrl,bypassSecurityTrustStyle,this.sanitizer.bypassSecurityTrustStyle(url(${this.UploaderService. test}));,我尝试了不同的方式在 HTML 中显示它:&lt;img src="this.UploaderService.test2 "&gt;, &lt;img [src]="this.UploaderService.test2"&gt; 也带有测试变量。我不知道我还能尝试什么。如果您有任何建议,请写下来,我会测试它。我在这个问题上挣扎了很长时间。
    • 你能给我发一个base64 url​​吗?这样我就可以重现这个?
    • 你的意思是我在 hello2 变量中使用 base64 编码的图像吗?
    【解决方案3】:

    这对我使用 base64 图像时有用。

    HTML:

    <img [src]="currVerifiedLoanOfficerPhoto">
    

    组件:

    this.currVerifiedLoanOfficerPhoto = 'data:image/jpg;base64,' + (this.sanitizer.bypassSecurityTrustResourceUrl(item) as any).changingThisBreaksApplicationSecurity;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 2013-11-17
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      相关资源
      最近更新 更多