Javascript: Convert image binary to base64 string

private convertImagetoURI(data): string {
let str = data.reduce(function (a, b) { return a + String.fromCharCode(b) }, ”);
return btoa(str).replace(/.{76}(?=.)/g, ‘$&\n’);
}

Considering that you get the image as binary data from an API call, use the above the function to pass the response and get back the string image.

Add it to you src in your image tag:

var imageSRC = ‘data:image/jpeg;base64,’ + this.convertImagetoURI(result.responseObject.Body)

<img src =imageSRC />

In angular2 you have to sanitize the string otherwise you  will get an xss error.

import DomSanitizer,

create a variable (e.g sanitizer :Domsanitizer)

use the bypassSecurity* functions

 

this.sanitizer.bypassSecurityTrustResourceUrl(‘data:image/jpeg;base64,’ + this.convertImagetoURI(result.responseObject.Body)) as string;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: