简体   繁体   English

Phonegap | 将imageuri转换为base64 | 使用jQuery将其上传到服务器后得到黑色图像

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

I want a valid string of base64 from imageuri . 我想要imageuri的有效base64字符串。 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. 我还尝试了其他选项,但没有获得可靠的base64 imagedata的可靠解决方案。 I don't want to upload image using file-transfer method. 我不想使用文件传输方法上传图像。 I want to convert the imageuri in simple base64 string. 我想将imageuri转换为简单的base64字符串。 Please suggest me specific answer for the same. 请为我建议同样的具体答案。

Thanks 谢谢

Please note that I've not tested this within PhoneGap. 请注意,我尚未在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: 一种可能性是转向使用success()方法来处理返回值,一旦加载并绘制了图像,就会调用该返回值:

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 ,例如:

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 ). 根据PhoneGap使用的安全模型,您可能必须注意与CORS相关的问题(请参阅污染的画布可能不会导出 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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