Category Archives: Javascript frameworks

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
%d bloggers like this: