简体   繁体   中英

Phonegap | converting imageuri to base64 | getting black image after uploading it to server using jquery

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

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM