Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/38812993/base64-to-image-angular-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...