ArrayBuffer作为源(图像标签)/显示来自Blob的图像

时间:2018-12-11 12:11:45

标签: angular typescript

我正在尝试将arraybuffer设置为图像标签的来源。 看来我有2个问题。我的控制台正在记录:

  

获取不安全的数据:数据:图像/ jpg; base64,[对象ArrayBuffer]   网址:: ERR_UNKNOWN_URL_SCHEME

所以我的问题是:
1.如何将“ blob”转换为字符串?
(如有必要:2.如何删除不安全标志?)

html:

<img src="data:image/jpg;base64, {{blob}}">

ts(斑点已转移):

export class ImgViewerComponent implements OnInit {

    @Input('blob') blob: ArrayBuffer;

    constructor() { }

    ngOnInit() {
    }

}

1 个答案:

答案 0 :(得分:1)

好的,找到了一些好的解决方案:

  1. 将ArrayBuffer转换为字符串:

    function _arrayBufferToBase64( buffer ) {
      var binary = '';
      var bytes = new Uint8Array( buffer );
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++) {
         binary += String.fromCharCode( bytes[ i ] );
      }
      return window.btoa( binary );
    }
    
         

    ArrayBuffer to base64 encoded string

  2. 删除不安全的前缀:

    import {DomSanitizer} from '@angular/platform-browser';
    ...
    constructor(private sanitizer:DomSanitizer){}
    ...
    sanitize( url:string ) {
      return this.sanitizer.bypassSecurityTrustUrl(url);
    }
    
         

    How to avoid adding prefix “unsafe” to link by Angular2?

现在我的HTML如下所示:

<img [src]="sanitize('data:image/jpg;base64, ' + _arrayBufferToBase64(blob))">