Need to convert image url to base64 string

I am getting file url from server through request. I need to convert image to base64 string for database storage.

Please let me know how can i convert image url to base64 string in ionic 2

I’m using this function to do this (it creates a canvas)

convertToDataURLviaCanvas(url, outputFormat){
	return new Promise( (resolve, reject) => {
		let img = new Image();
		img.crossOrigin = 'Anonymous';
		img.onload = function(){
			let canvas = <HTMLCanvasElement> document.createElement('CANVAS'),
			ctx = canvas.getContext('2d'),
			canvas.height = this.height;
			canvas.width = this.width;
			ctx.drawImage(this, 0, 0);
			dataURL = canvas.toDataURL(outputFormat);
			canvas = null;
		img.src = url;

and I call it using:

this.convertToDataURLviaCanvas(someUrl, "image/jpeg")
.then( base64Img => {
   //do whatever you need here, with the base64 data

By the way, this has nothing to do with Ionic. It’s pure javascript (except for the , needed for TypeScript compiler).


i think the following code as correct way convert your url image

<ion-item *ngIf=“jobs.Signature”>

        <ion-icon item-left name="create"></ion-icon>
        <img src="data:image/JPEG;base64,{{jobs.Signature}}">



<ion-item *ngIf=“jobs.Photo”>

        <ion-icon item-left name="camera"></ion-icon>
        <img src="data:image/JPEG;base64,{{jobs.Photo}}">


ctx.drawImage(this, 0, 0);
in this above line i got an error in “this”

you just have to replace this with img

1 Like