0

I want a valid string of base64 from imageuri. I have use below code for this but it's getting black image after uploading it to the server.

function encodeImageUri(imageUri)
{
     var c=document.createElement('canvas');
     var ctx=c.getContext("2d");
     var img=new Image();
     img.onload = function(){
       c.width=this.width;
       c.height=this.height;
       ctx.drawImage(img, 0,0);
     };
     img.src=imageUri;
     var dataURL = c.toDataURL("image/jpeg");
     return dataURL;
}

I have also tried other options but not getting solid solution to get the valid base64 imagedata. I don't want to upload image using file-transfer method. I want to convert the imageuri in simple base64 string. Please suggest me specific answer for the same.

Thanks

  • 1
    You need to remove anything before and including **,** before dumping the content to image on the server side. Which I think you missed. Refer: http://stackoverflow.com/questions/15153776/convert-base64-string-to-an-image-file Although PHP but will give a decent Idea – Akshay Khandelwal Mar 16 '17 at 14:18
  • it is properly working for getPicture method with navigator.camera.DestinationType.DATA_URL, but I'm not able to convert the image uri into base64 string. – Pankaj Bhandarkar Mar 16 '17 at 14:20

1 Answers1

0

Please note that I've not tested this within PhoneGap.

It's possible you're being caught out by the image being loaded asynchronously; you're encoding it into a string before it's actually loaded and processed in full.

There are various ways of handling this; one possibility is to move to using a success() method to handle the return value, which will be called once the image has loaded and been drawn:

function encodeImageUri(imageUri, success)
{
     var c=document.createElement('canvas');
     var ctx=c.getContext("2d");
     var img=new Image();
     img.onload = function(){
       c.width=this.width;
       c.height=this.height;
       ctx.drawImage(img, 0,0);
       success(c.toDataURL("image/jpeg"));       
     };

     img.src=imageUri;
}

You will then need to call encodeImageUri with a function that will handle the end result, for example:

encodeImageUri(" < url > ", function (data) {
    console.log(data);
});

Depending upon the security model PhoneGap uses, you may have to look out for CORS-related issues (see Tainted canvases may not be exported).

Community
  • 1
  • 1
Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50
  • Be aware that this isn't by any means a perfect solution - ideally you would also have an error handler here, for example. – Adrian Wragg Mar 16 '17 at 15:29