Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASE64 to image angular 2

I'm trying to show an image get from a remote server with angular 2.

In my component I have an object that is an "university_info" object that is my model.

export class myClass
{
    university_info : university_info;
}
myFunction()
{
    this.university_info = new university_info(responseFromServer[image])
}

export class university_info
{
    imageBase64 : string
    constructor(image : string)
    {
        this.imageBase64 = image
    }
}

All is working fine. I get base64 image but when I try to show it in HTML in this way :

  <img [src]="'data:image/jpg;base64,'+university_info.imageBase64" />

That's is what I get :

enter image description here

enter image description here

enter image description here

like image 875
Marco Castano Avatar asked Aug 07 '16 10:08

Marco Castano


People also ask

How can I convert Base64 image to typescript?

If you have a data url and you want it to be shown in an img element, just set the src to the data url. You don't need to convert it to an image. Even so, just use the image as your feed to the <image-cropper>. Just create an image, set the src to the data URL, and use that image for your <image-cropper>.

What is Data Image PNG Base64?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).


2 Answers

I feel like this thread lacks concrete examples which made me have some difficulties:

Import DomSanitizer:

import { DomSanitizer } from '@angular/platform-browser';

define in constructor:

constructor(private _sanitizer: DomSanitizer) { }

Sanitize the Base64 string you want to pass as your image source (use trustResourceUrl):

this.imagePath = this._sanitizer.bypassSecurityTrustResourceUrl('data:image/jpg;base64,' 
                 + toReturnImage.base64string);

Bind to html:

<img [src]="imagePath">
like image 74
DGK Avatar answered Oct 23 '22 13:10

DGK


Solution: Just use 'data:image/jpg;base64' into your image tag like this

<img src="{{'data:image/jpg;base64,' + imagePath}}" />
like image 40
Rahul Jograna Avatar answered Oct 23 '22 11:10

Rahul Jograna