Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Web and WebWorks Development

Posts: 116
Registered: ‎03-15-2011
My Device: Blackberry 9800
My Carrier: developer
Accepted Solution

Getting incorrect Base64 string of image from toDataURL() for the first time in blackberry 10 webworks

[ Edited ]


I need to get Contact image converted to Base64 string using BB 10 Webworks (blackberry.pim.contacts) as I am only getting the contact.photos[0].smallFilePath which is returning the file path from the phonebook.


Now i want to get image from this path and convert it into Base64 string.

Below is the code of javascript:


var img = document.createElement('Image');
var canvas = document.createElement('Canvas');


function getBase64Image(p){
   img.setAttribute("src", p);

   canvas.width = img.width;

   canvas.height = img.height;

   var ctx = canvas.getContext("2d");
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL("image/jpg");



This is returning wrong Base64 string of image for the first time. When i convert this string to image it displays white screen. But returns perfect string at secong time and after conversion, displays correct image.


I am using Blackberry Z10(OS 10) for testing .


i think canvas is not drawing image properly for the first time.

I searched and tried a lot but didn't get success.What will be the solution.


Thanks in Advance.

Posts: 1,561
Registered: ‎04-12-2010
My Device: BlackBerry Z10
My Carrier: Bell

Re: Getting incorrect Base64 string of image from toDataURL() for the first time in blackberry 10 webworks

My guess is that the image hasn't loaded the source fully yet. Setting the src / loading the image is an asynchronous event, meaning your code will continue to the next line regardless of whether the image has loaded yet or not.

After you call setAttribute, instead of executing the canvas code, you will likely need to set an event listener on img for the load event. Once the image has loaded, you can then use the img variable with canvas to retrieve its data.

Note that getBase64 will return immediately, so you may need to either design some sort of wait mechanism before returning, or embrace the asynchronous approach and integrate callbacks for success to trigger the next piece of code.

Erik Oros | @WaterlooErik | eoros@blackberry.com | Developer Issue Tracker

If a reply has answered your question, please click Accept as Solution to help other visitors in the future.