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 :
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>.
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).
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">
Solution: Just use 'data:image/jpg;base64'
into your image tag like this
<img src="{{'data:image/jpg;base64,' + imagePath}}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With