5

I'm trying to set an arraybuffer as source of an image tag. It seems that I've got 2 problems. My console is logging:

GET unsafe:data:image/jpg;base64, [object ArrayBuffer] net::ERR_UNKNOWN_URL_SCHEME

so my question is:
1. How do I convert my 'blob' to a string?
(if necessary: 2. How to remove the unsafe flag?)

html:

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

ts (blob is transferred):

export class ImgViewerComponent implements OnInit {

    @Input('blob') blob: ArrayBuffer;

    constructor() { }

    ngOnInit() {
    }

}
guwluws
  • 211
  • 1
  • 3
  • 13

1 Answers1

10

Okay found some good solutions:

  1. Converting ArrayBuffer to string:

    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. Remove the unsafe prefix:

    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?

Now my Html looks like the following:

<img [src]="sanitize('data:image/jpg;base64, ' + _arrayBufferToBase64(blob))">
guwluws
  • 211
  • 1
  • 3
  • 13
  • Hello, This solution worked for me. But I want to open image or file in another tab, How can i achieve the same using this solution? Thank you. – Akshay Dusane Apr 14 '20 at 08:25
  • @AkshayDusane You can wrap the image tag with href. It'll pass your image to the link as content. See this question https://stackoverflow.com/questions/3139811/how-to-link-an-image-and-target-a-new-window – guwluws Apr 15 '20 at 11:41
  • Excellent post. Worked very well! Thank you so much. – Antti A Feb 18 '21 at 21:21