Convert the image returned from the Cordova Contacts Plugin to base64 (iOS)


#1

After I’ve retrieved a contact image from the Cordova Contacts Plugin on iOS, I would like to encode it to base64. Here is my code to do so:

var c = document.createElement("canvas");
var ctx = c.getContext("2d");
var img = document.createElement("img");
img.src = "file:///" + contact.photos[0].value;
ctx.drawImage(img, 100, 100);
console.log(c.toDataURL());

However, every time I try this, the console outputs an empty image. What am I doing wrong?


How to save a contact to iOS address book with an image?
#2

your need to wait until the image is ready and loaded
add a listener to img.onload.

img.onload = function () {
  ctx.drawImage(img, 100, 100);
  console.log(c.toDataUrl());
};
img.src = ".....";

#3

Hm, it still isn’t working. The image logged to the console is the same.


#4

Any ideas on this? For the life of me I cannot figure out how to do it.


#5

Look at this example:
http://www.html5canvastutorials.com/tutorials/html5-canvas-images/

there the canvas is already in the dom, but you can create it before


#6

I’ll check it out. Thanks.