PhoneGap图片拍照上传,边修改上传程序边学习when.js
在项目中很多的APP都需要上传头像的功能,目前在我的代码来面发现一个bug,先贴上代码
1 var pictureSource; //图片来源 2 var destinationType; //返回的图片数据格式 3 4 5 6 document.addEventListener("deviceready",onDeviceReady,false); 7 8 // 设备初始化之后调用 9 function onDeviceReady() { 10 pictureSource=navigator.camera.PictureSourceType; 11 destinationType=navigator.camera.DestinationType; 12 13 //拍照 14 $("#photograph").click(function(){ 15 capturePhoto(); 16 addMaskLayout(); 17 18 }); 19 20 $("#PhotoSelect").click(function(){ 21 getPhoto(pictureSource.SAVEDPHOTOALBUM); 22 addMaskLayout(); 23 }); 24 25 26 //检测网络状态 27 /* 28 document.addEventListener("online",function(){ 29 ShowMsg("网络已连接"); 30 },false) 31 document.addEventListener("offline",function(){ 32 ShowMsg("网络已断开"); 33 },false)*/ 34 35 } 36 37 38 //获取拍照照片 39 function capturePhoto() { 40 navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 30, 41 destinationType: destinationType.DATA_URL }); 42 } 43 44 45 //从相册中获取照片 46 function getPhoto(source) { 47 navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 30, 48 destinationType: destinationType.DATA_URL, 49 sourceType: source }); 50 } 51 52 //拍照取消或者拍照失败调用函数 53 function onFail(message) { 54 ShowMsg("获取照片失败"); 55 } 56 57 function onPhotoDataSuccess(imgData){ 58 59 60 setTimeout(function(){render(imgData)},5000); 61 62 //setTimeout(sendImg(),3000); 63 64 } 65 66 var MAX_HEIGHT = "85"; 67 function render(src){ 68 var image = new Image(); 69 image.onload=function(){ 70 //创建一个Canvas 71 //var canvas = document.getElementById("myCanvas"); 72 var canvas = document.createElement("canvas"); 73 //如果高度超标 74 if(image.height > MAX_HEIGHT){ 75 image.width *= MAX_HEIGHT / image.height; 76 image.height = MAX_HEIGHT; 77 } 78 79 //获取Canvas的2D环境对象,可以理解Canvas是个房子,而 Context是管理员 80 var ctx = canvas.getContext("2d"); 81 //canvas清屏 82 ctx.clearRect(0,0,canvas.width,canvas.height); 83 //重置Canvas宽高 84 canvas.width = image.width; 85 canvas.height=image.height; 86 87 //将图像绘制到Canvas上 88 ctx.drawImage(image,0,0,image.width,image.height); 89 90 //发送给后台 91 var dataUrl = canvas.toDataURL("image/png",0.6); 92 dataUrl = dataUrl.slice(22); 93 94 setTimeout(function(){sendImg(dataUrl)},2000); 95 }; 96 image.src = "data:image/png;base64,"+src; 97 } 98 99 100 function sendImg(dataUrl){ 101 102 103 //var canvas = document.getElementById("myCanvas"); 104 105 106 107 108 //console.log(dataUrl); 109 //放入到img 110 // 111 112 var url = baseUrl+"&c=member&a=checkinfobytype"; 113 var type = 2; 114 115 var userData =new UserData(); 116 var uid = userData.getUserValue("member_id"); 117 118 var loadingObj = new Loading(); 119 loadingObj.show(); 120 121 $.post(url,{type:type,uid:uid,message:dataUrl},function(data){ 122 123 if(data && data.status == "001"){ 124 125 loadingObj.clear(); 126 127 ShowMsg("上传成功"); 128 if(data.imgurl){ 129 var userData =new UserData(); 130 userData.setUserValue("member_headimg",data.imgurl); 131 } 132 $("#userInfo_section_topHeadPortrait").attr("src","data:image/png;base64,"+dataUrl); 133 134 }else{ 135 loadingObj.clear(); 136 ShowMsg(data.msg); 137 138 } 139 $("#clearMaskLayout").addClass("maskLayoutHidder"); 140 $("#alterHeadPortrait").addClass("maskLayoutHidder"); 141 142 },"json") 143 }
通过以上代码基本上可以实现以下功能:
- 打开照相机和相册(依赖于phonegap插件)
- Canvas压缩
- 图片上传
但是,在安卓手机中会出现手机拍照返回主界面,并且后面代码不执行的情况:
简单点说,第一拍照完,然后程序自动返回到主界面,然后,再弹回到上传的页面,但是,向服务器上传的动作就不执行了,而然,当你再执行一次拍照功能,接着会重复上面的流程,但是不同的是,程序却开始执行上传功能,不过,上传的是上次的拍过的之后的照片。
解决的办法:经过网络搜索,手机拍照得到的数据分为两种:图片的URL和base64数据,官方推荐前者,后者会照成内存问题。所以,我就换了一下方式。
code:
var pictureSource; //图片来源 var destinationType; //返回的图片数据格式 document.addEventListener("deviceready",onDeviceReady,false); // 设备初始化之后调用 function onDeviceReady() { pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType; //拍照 $("#photograph").click(function(){ takePicture().then(uploadPicture).then(deletePictureFromCache); }); //从相册选择 $("#PhotoSelect").click(function(){ //getPhoto(pictureSource.SAVEDPHOTOALBUM); //addMaskLayout(); selectPhoto_Picture().then(uploadPicture).then(deletePictureFromCache); }); } /****使用文件位置上传************/ //相册选择上传 function selectPhoto_Picture(){ var deferred = when.defer(), destinationType=navigator.camera.DestinationType, options = { quality: 100, destinationType: destinationType.FILE_URI, sourceType: Camera.PictureSourceType.PHOTOLIBRARY, //cameraDirection: Camera.Direction.FRONT, targetWidth: 240, targetHeight: 320, correctOrientation: true }; navigator.camera.getPicture(function(data){ deferred.resolve(data); }, null, options); return deferred.promise } // 打开摄像头拍照 function takePicture() { var deferred = when.defer(), destinationType=navigator.camera.DestinationType, options = { quality: 100, destinationType: destinationType.FILE_URI, //sourceType: Camera.PictureSourceType.PHOTOLIBRARY, //cameraDirection: Camera.Direction.FRONT, targetWidth: 240, targetHeight: 320, correctOrientation: true }; navigator.camera.getPicture(function(data){ deferred.resolve(data); }, null, options); return deferred.promise } // 上传图片到服务器 function uploadPicture( imageURI ){ var deferred = when.defer(), options = new FileUploadOptions(); options.fileKey = "message"; options.fileName = "message"; options.mimeType = "image/jpeg"; var ft = new FileTransfer(); // 上传回调 ft.onprogress = showUploadingProgress; var uid = userData.member_id; var url = baseUrl + "&c=member&a=checkinfobytype&type=2&uid="+uid; ft.upload( imageURI, encodeURI(url), function(r){ var response = r.response; var result = JSON.parse(response); if(result.status === "001"){ ShowMsg("上传成功"); }else{ ShowMsg("上传失败,我要再试一次。") } $("#uploadProgress").addClass("hiddenProgress"); deferred.resolve( imageURI ); } , null, options); //alert("3"); return deferred.promise; } // 显示上传进度 function showUploadingProgress( event ){ $("#uploadProgress").removeClass("hiddenProgress"); if (event.lengthComputable) { var complete = (event.loaded / event.total * 100 | 0); var progress = document.getElementById('uploadprogress'); progress.value = progress.innerHTML = complete; } } // 从缓存中删除图片 function deletePictureFromCache( imageURI ){ window.resolveLocalFileSystemURI(fileURI, function( fileEntry ){ fileEntry.remove(); }, null); }
再此说一下,经过测试,好像是能在IOS中没有问题,但是Android中却不能使用。
其中,上传的进度条,要特别声明下,本来是用的phonegap的上传控件(navigator.notification.progressStart(),navigator.notification.progressStop(),navigator.notification.progressValue)这些的,发现这个控件在phonegap 2.9.1的android版本是有这些东西的,但是在IOS的phonegap 2.9.1却没有。
好了,暂时到这!