I am fetching an image via a http request which returns a blob and i want to assign the blob returned to an image src.
http request:
const options = {
headers,
responseType: 'blob' as 'json'
};
return this.httpClient.get(url, options)
component.ts
async ngOnInit() {
this.frontImageSrc = getImage()
}
async getImage() {
const image = await this.service.imageRequest(id, "front", token).toPromise();
var imageUrl = URL.createObjectURL(image)
return imageUrl
}
component.html
<img src={{frontImageSrc}} alt="image"/>
The image src does not get assigned and in the console i can see the following.
blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2 14:00:00.664 unsafe:blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2:1 GET unsafe:blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2 net::ERR_UNKNOWN_URL_SCHEME
getContext("2d"); // Get the "context" of the canvas var img = document. getElementById("myimage"); // The id of your image container ctx. drawImage(img,0,0,width,height); // Draw your image to the canvas var jpegFile = canvas. toDataURL("image/jpeg"); // This will save your image as a //jpeg file in the base64 format.
Binary Large Object(Blob) is an Object used to store or holding data in a browser. Blobs can be used to read then save data on disk. A Blob object has properties to represent the size and MIME type of stored file. This can be used as a normal file.
You can convert your string into a Uint8Array to get the raw data. Then create a Blob for that data and pass to URL. createObjectURL(blob) to convert the Blob into a URL that you pass to img. src.
A Binary Large Object ( BLOB ) is a MySQL data type that can store binary data such as images, multimedia, and PDF files.
Message about :unsafe
stuff means that angular sanitised your url, because it considers it unsafe. Cleanest way to work this around is to introduce a pipe (although it is not necessary): like so:
@Pipe({ name: 'safeResourceUrl' })
export class SafeUrlPipe implements PipeTransform {
constructor(private readonly sanitizer: DomSanitizer) {}
public transform(url: string): SafeResourceUrl {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
Then in your component you can the following:
component.html
<img [src]="frontImageSrc | safeResourceUrl" alt="image"/>
component.ts
async ngOnInit() {
this.frontImageSrc = getImage()
}
async getImage() {
const image = await this.service.imageRequest(id, "front", token).toPromise();
var imageUrl = URL.createObjectURL(image)
return imageUrl
}
ngOnDestroy() {
URL.revokeObjectURL(this.imageUrl)
}
Of course you can do bypassing in your ngOnInit
instead, but it's cleaner to use pipe. Also since url is created asynchronously it might make sense to do a null check in the template.
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