1

I need to Encode an image to Base64 format and then I have to Decode the Base64 value to an image and display the image in a HTML Page. Now I encoded an Image to base64 with the below code,

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);
 }

Im getting the base64 value now t couldn't able to convert the base64 value to an image.

Depi
  • 17
  • 1
  • 2
  • 8
  • I think you should also be able to just set the src of the image to your base 64 string. Do not forget to add `data:image/jpeg;base64,` in front of your base 64 string – BrianM May 08 '18 at 09:06
  • Yup I forgot to add that. Now working.@BrianM – Depi May 08 '18 at 10:00

3 Answers3

0

BASE64 to image angular 2

You can try to use _sanitizer.bypassSecurityTrustUrl to tell angular src value is safe. Take a look at this class from angular:

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
}

and be low an example for safe html:

export class AppComponent {

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

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

constructor(private _sanitizer: DomSanitizationService){}

}

Chaitanya Kumar
  • 212
  • 2
  • 13
0

I think you should also be able to just set the src of the image to your base 64 string. Do not forget to add data:image/jpeg;base64, in front of your base 64 string

BrianM
  • 951
  • 2
  • 12
  • 29
-1

Got Output with the below code:

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