Fetch an image from Url In angular 4+ and store locally

Balvinder Singh
3 min readOct 13, 2018

--

Hi, everyone, I was working on some project with social login, so we need to fetch the user image and save to our database. So, I looked over some web pages and got a solution.

Here is the working snippet from Faisal, who shared the solution on stack overflow.

Code snippet on Stackblitz

So what we need to do is.

  1. First, we set up a method to create an image object and set URL property to that image. Url is the one we need to fetch the image from.
getBase64ImageFromURL(url: string) {
return Observable.create((observer: Observer<string>) => {
// create an image object
let img = new Image();
img.crossOrigin = 'Anonymous';
img.src = url;
if (!img.complete) {
// This will call another method that will create image from url
img.onload = () => {
observer.next(this.getBase64Image(img));
observer.complete();
};
img.onerror = (err) => {
observer.error(err);
};
} else {
observer.next(this.getBase64Image(img));
observer.complete();
}
});
}

2. The method that will create the base64 image from the image object we created by setting the URL to fetch the required image.

getBase64Image(img: HTMLImageElement) {
// We create a HTML canvas object that will create a 2d image
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
// This will draw image
ctx.drawImage(img, 0, 0);
// Convert the drawn image to Data URL
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");}

3. Now create a method in ngOninit() to call this method we created previously.

ngOnInit() { // for testing you can add any image url here or get dynamically  from other methods as you require
let imageUrl = '';

this.getBase64ImageFromURL(imageUrl).subscribe(base64data => {
console.log(base64data);
// this is the image as dataUrl
this.base64Image = 'data:image/jpg;base64,' + base64data;
});
}

4. As we get the image as a dataUrl, we now have the image as local. We can display image by giving `src=”dataURL”`or We can store and use this data URL in DB, but the size is very large, also the length of the string object we get. So we need to convert the base64 image to some better recognizable format, so we need to create an image of type png/jpeg from this.

For this I have already added a post, go check out the link below.

So, I hope you have enjoyed reading this post, and also the solution for fetching and creating images from URL.
If you like the post pls, clap for me it keeps me motivated to share more post like these. Also, do follow my blog tekraze.com, the link is below.

--

--

Balvinder Singh
Balvinder Singh

Written by Balvinder Singh

Open Source FullStack Developer | Blogger | Crypto Enthusiast | Gamer