【问题标题】:How to decode Base64 to Image in angular2如何在angular2中将Base64解码为图像
【发布时间】:2018-05-08 08:33:17
【问题描述】:

我需要将图像编码为 Base64 格式,然后我必须将 Base64 值解码为图像并在 HTML 页面中显示图像。现在我使用以下代码将图像编码为 base64,

getFiles(event) {
      this.files = event.target.files;
      //alert(this.files);
      var reader = new FileReader();
      reader.onload = this._handleReaderLoaded.bind(this);
      reader.readAsBinaryString(this.files[0]);
      //alert(this.files[0]);
  }

  _handleReaderLoaded(readerEvt) {
      var binaryString = readerEvt.target.result;
      this.filestring = btoa(binaryString);  // Converting binary string data.
     //alert(this.filestring);
      //console.log(this.filestring);
 }

我现在获取 base64 值无法将 base64 值转换为图像。

【问题讨论】:

  • 我认为您也应该能够将图像的 src 设置为 base 64 字符串。不要忘记在你的 base 64 字符串前面添加data:image/jpeg;base64,
  • 是的,我忘了补充。现在工作。@BrianM

标签: html angular


【解决方案1】:

BASE64 to image angular 2

您可以尝试使用 _sanitizer.bypassSecurityTrustUrl 来告诉 angular src 值是安全的。从角度看一下这个类:

class DomSanitizationService {
sanitize(context: SecurityContext, value: any) : string
bypassSecurityTrustHtml(value: string) : SafeHtml
bypassSecurityTrustStyle(value: string) : SafeStyle
bypassSecurityTrustScript(value: string) : SafeScript
bypassSecurityTrustUrl(value: string) : SafeUrl
bypassSecurityTrustResourceUrl(value: string) : SafeResourceUrl
}

并成为安全 html 的示例:

导出类 AppComponent {

private _htmlProperty: string = '<input type="text" name="name">';

public get htmlProperty() : SafeHtml {
   return this._sanitizer.bypassSecurityTrustHtml(this._htmlProperty);
}

constructor(private _sanitizer: DomSanitizationService){}

}

【讨论】:

    【解决方案2】:

    我认为您也应该能够将图像的 src 设置为您的 base 64 字符串。不要忘记在你的 base 64 字符串前面添加data:image/jpeg;base64,

    【讨论】:

      【解决方案3】:

      使用以下代码得到输出:

      <img [src]="'data:image/jpg;base64,'+filestring" style="height:500px;width:500px" />
      

      【讨论】:

        猜你喜欢
        • 2020-01-13
        • 2018-09-05
        • 1970-01-01
        • 2014-06-12
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 2018-11-22
        • 2021-11-20
        相关资源
        最近更新 更多