Vue.js 使用cordova camera插件调取相机

来源:互联网 发布:ios系统解压缩软件 编辑:程序博客网 时间:2024/05/29 02:45

介绍完上文 用Cordova打包Vue项目之后,本文给出在vue.js里如何使用cordova的插件完成调取相机及图库,并完成图片上传的操作。

具体的操作步骤如下

第一步:在cordova项目下安装cordova-plugin-camera插件

cordova plugin add cordova-plugin-camera

第二步:在需要调取相机的地方,加入相关的代码

 cameraTakePicture: function (mySourceType) {    navigator.camera.getPicture(this.onSuccess, this.onFail, {        quality: 50,        destinationType: Camera.DestinationType.DATA_URL,        encodingType: Camera.EncodingType.JPEG,        sourceType: mySourceType    }) },

注意的问题:

1、sourceType:

PHOTOLIBRARY 或 0 打开照片库。CAMERA 或 1 打开本机相机。SAVEDPHOTOALBUM 或 2 打开已保存的相册。

2、destinationType

DATA_URL 或 0 返回base64编码字符串。FILE_URI 或 1 返回图片文件URI。NATIVE_URI 或 2 返回图片本机URI。

第三步:在上步完成图片拍摄之后,图片上传

由于后台采用的是阿里云的追加上传,接收的参数类型为File,因此,在上步得到的base64图片需要转换为File,

dataURLtoFile: function (dataurl, filename) {    var arr = dataurl.split(',')    var mime = arr[0].match(/:(.*?);/)[1]    var bstr = window.atob(arr[1])    var n = bstr.length    var u8arr = new Uint8Array(n)    while (n--) {      u8arr[n] = bstr.charCodeAt(n)    }    var blob = new Blob([u8arr], {type: mime})    blob.lastModifiedDate = new Date()    blob.name = filename    return blob}
调用的方法如下

var file = this.dataURLtoFile('data:image/jpeg;base64,' + imageURI, 'test.jpeg')
imageURI是onSuccess函数的参数
至此,上传图片已经可以采用阿里云的追加上传完成了,具体的代码不附了

第四步:使用mintUI的popup完成点击弹出选择相机还是图库打开

首先,import {Popup} from 'mint-ui'

然后在components里加入Popup

最后在html里加入

<mt-popup v-model="popupVisible" position="bottom" style="width: 100%;">    <div>      <div class='popup-item' @click='TakePictureType(1)'>相机</div>      <div class='popup-item' @click='TakePictureType(2)'>图库</div>    </div></mt-popup>
其中,popupVisible控制是否弹出,position控制弹出的位置,里面的具体内容放在一个div里了
至此,完成了选择相机还是图库的操作。

第五步:打包apk,安装到手机上进行测试

以上就是在用cordova的camera插件进行图片上传的时候遇到的问题及解决步骤,如有问题,欢迎指出~

ios拍照旋转问题的解决

在ios上,拍照时会出现旋转的情况,设置correctOrientation:true  即可解决


参考网址:

[1] https://github.com/apache/cordova-plugin-camera

[2] http://blog.csdn.net/michael_ouyang/article/details/75085648

[3] https://www.w3cschool.cn/cordova/cordova_camera.html

[4] https://www.alibabacloud.com/help/zh/doc-detail/32013.htm?spm=a3c0i.o32103zh.b99.105.54c6bd9b5mnXol

[5] https://zhuanlan.zhihu.com/p/21802181

[6] http://blog.csdn.net/blueling51/article/details/51668573

原创粉丝点击