cordova camera插件——摄像头插件的使用及上传图片

来源:互联网 发布:java语言和c语言 编辑:程序博客网 时间:2024/05/24 06:21


介绍

cordova提供照相机API与设备相机进行交互。

通过照相机API、我们可以拍摄或者访问照片库中的照片,返回图片的base64编码字符串或者图片的url文件路径。

 

 

 

安装插件

需要cordova 5.0以上版本

cordova plugin add cordova-plugin-camera

通过ID安装旧版本的cordova

cordova plugin add org.apache.cordova.camera

当然,也可以通过下载直接添加:(不稳定)

cordova plugin add https://github.com/apache/cordova-plugin-camera.git




 

使用方法:

这个插件定义了一个全局的navigator.camera 对象,它提供了一个API,用于拍照和从系统图库中选择图像。

虽然对象是附加到全局的navigator对象内,但是需要deviceready事件之后才可用

document.addEventListener("deviceready", onDeviceReady, false);function onDeviceReady() {    console.log(navigator.camera);}




API 参考



navigator.camera.getPicture

使用camera.getPicture,可以调用设备默认的摄像头拍照,或从设备相册中获取一张照片照片将以base64编码的字符串或图片URI形式返回

 

navigator.camera.getPicture的参数:



示例:

拍一张照片,并返回它的一个 base64 编码的图像:

    navigator.camera.getPicture(onSuccess, onFail, { quality: 50,        destinationType: Camera.DestinationType.DATA_URL    });        function onSuccess(imageData) {        var image = document.getElementById('myImage');        image.src = "data:image/jpeg;base64," + imageData;    }        function onFail(message) {        alert('Failed because: ' + message);    }

拍一张照片和返回图像文件的位置:

navigator.camera.getPicture(onSuccess, onFail, { quality: 50,        destinationType: Camera.DestinationType.FILE_URI     });        function onSuccess(imageURI) {        var image = document.getElementById('myImage');        image.src = imageURI;    }        function onFail(message) {        alert('Failed because: ' + message);    }



namera.cleanup()

移除掉中间图像文件是调用camera.getPicture所保存在临时的存储空间。

只适用于当Camera.sourceType的值=Camera.PictureSourceType.CAMERACamera.destinationType =Camera.DestinationType.FILE_URI

 

Supported Platforms 支持平台

· iOS


示例:

navigator.camera.cleanup(onSuccess, onFail);function onSuccess() {    console.log("Camera cleanup success.")}function onFail(message) {    alert('Failed because: ' + message);}




CameraError

onError 的回调函数提供了一条错误信息。

    function(message) {        // Show a helpful message    }

参数

message    消息提供的设备的本机代码





CameraSuccess

成功访问图片后的回调函数,该函数的参数取值取决于destinationType的类型,如果destinationTypeDATA_URI,则该参数返回Base64编码的图片数据;如果destinationTypeFIEL_URI,则该参数返回的是图片的URI

不论是图像数据或者URI,都可以通过img标签的src属性显示在网页中,

如对于图片数据imageData,通过给src属性赋值”data:image/jpeg:base64,”+imageData即可,

而对于图片URI imageURI,通过给src属性直接赋值imageURI即可。

    function(imageData) {        // Do something with the image    }


参数

 imageData   Base64 编码进行编码的图像资料,或图片文件的 URI,取决于 `cameraOptions` 效果。


示例:返回的base64设置到img标签中

    function cameraCallback(imageData) {        var image = document.getElementById('myImage');        image.src = "data:image/jpeg;base64," + imageData;    }



CameraOptions

相机设置的可选参数。

名字

类型

默认值

描述

quality

number50图像的保存质量,范围0-100,100是最大值,最高的分辨率,没有任何压缩损失(请注意有关该相机的分辨率信息不可用。)destinationTypeDestinationTypeFILE_URI选择返回值的格式sourceTypePictureSourceType        CAMERA获取图片的来allowEditBooleantrue允许在选择图片之前进行简单的编辑encodingTypeEncodingTypeJPEG选择图像的返回编码targetWidthnumber 宽度像素用来缩放图像。必须和targetHeight一起使用。宽高比保持不变。targetHeightnumber  高度像素用来缩放图像。必须和targetWidth一起使用。宽高比保持不变mediaTypeMediaTypePICTURE                       选择media类型。它只适用PictureSourceType是PHOTOLIBRARY或SAVEDPHOTOALBUMcorrectOrientation                   Boolean 如果是横向拍摄的照片,会自动旋转到正确的方向saveToPhotoAlbum                                   Boolean 设备拍照后的图像是否保存的图片库中popoverOptionsCameraPopoverOptions                                          仅ios可用,设定在ipad的popover的位置cameraDirectionDirectionBACK选择前置摄像头还是后置摄像头



























Camera.DestinationType :枚举
类型:相机的静态枚举属性
特性:
变量名类型默认值描述DATA_URLnumber0返回Base64编码的字符串FILE_URInumber1返回文件的URI(content://media/external/images/media/2 for Android)NATIVE_URInumber2返回原生URI (eg. asset-library://... for iOS)


Camera.EncodingType :枚举
类型:相机的静态枚举属性
特性:
变量名类型默认值描述JPEGnumber0返回JPEG的图片PNGnumber1返回PNG的图片


Camera.MediaType :枚举
类型:相机的静态枚举属性
特性:
变量名类型默认值描述PICTUREnumber0仅允许选择静态影像。 默认。将通过DestinationType返回指定格式VIDEOnumber1仅允许选择视频,只返回网址ALLMEDIAnumber2允许返回所有媒体格式

Camera.PictureSourceType :枚举
类型:相机的静态枚举属性
特性:
变量名类型默认值描述PHOTOLIBRARYnumber0从设备相册选择图片CAMERAnumber1用摄像头拍摄图片SAVEDPHOTOALBUMnumber2从设备相册选择图片(一个应该是ios一个安卓)

Camera.PopoverArrowDirection :枚举
匹配的iOS UIPopoverArrowDirection在popover固定的箭头位置。
类型:相机的静态枚举属性
特性:
变量名类型默认值ARROW_UPnumber1ARROW_DOWNnumber2ARROW_LEFTnumber4ARROW_RIGHTnumber8ARROW_ANYnumber15

Camera.Direction :enum
类型:相机的静态枚举属性
特性:
变量名类型默认值描述BACKnumber0使用后置摄像头FRONTnumber1使用前置摄像头

CameraPopoverOptions
iOS特供,从iPad的系统相册选择图片,指定popover的定位元素的位置箭头方向和参数。需要注意的是popover的尺寸可以改变,以适应屏幕的箭头和取向方向。确保指定元素位置时考虑方向变化。变量名类型默认值描述[x]number0屏幕选取框的x坐标[y]number32屏幕选取框的y坐标[width]number320屏幕选取框的宽度[height]number480屏幕选取框的高度[arrowDir]PopoverArrowDirectionARROW_ANY确定popover的指向






示例

示例一:使用camera插件,从图片库中选择图片,返回base64编码字符串

index.html

<!DOCTYPE html><html><head>    <meta charset="UTF-8"/>    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">    <meta name="format-detection" content="telephone=no">    <meta name="msapplication-tap-highlight" content="no">    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">    <title>Hello World</title>    <style>        .line {            padding: 5px;        }    </style></head><body><div class="app">    <div class="line"><button id="openLabrary">按钮</button></div>    <div class="line"><img id="myImage" style="height: 200px;"></img></div></div><script type="text/javascript" src="cordova.js"></script><script type="text/javascript" src="js/index.js"></script></body></html>

 

 

index.js

var app = {    // Application Constructor    initialize: function() {        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);    },    // deviceready Event Handler    onDeviceReady: function() {        this.receivedEvent();    },    $$: function(id) {        return document.getElementById(id);    },    receivedEvent: function(){        var _this = this;        var getDomLabrary = this.$$('openLabrary');        getDomLabrary.onclick = function(){            // 打开图片库            navigator.camera.getPicture(onSuccess, onFail, {                quality: 50,                                       // 相片质量是50                sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM, // 设置从图片库获取                destinationType: Camera.DestinationType.DATA_URL       // 以base64返回            });            function onSuccess(imageData) {                console.log(imageData)                _this.$$('myImage').src = "data:image/jpeg;base64," + imageData;            }            function onFail(message) {                alert('Failed because: ' + message);            }        }    }};app.initialize();


运行:

点击按钮,显示相册,选择图片

图片被添加到页面上



注意:

返回base64编码字符串是没有data:image/jpeg;base64,头部的!!!







示例二:

使用camera插件,打开摄像头拍照,返回照片的文件路径,并显示在页面上

index.html

<!DOCTYPE html><html><head>    <meta charset="UTF-8"/>    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">    <meta name="format-detection" content="telephone=no">    <meta name="msapplication-tap-highlight" content="no">    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">    <title>Hello World</title>    <style>        .line {            padding: 5px;        }        #myImage {            height: 200px;        }    </style></head><body><div class="app">    <div class="line"><button id="openLabrary">按钮</button></div>    <div class="line"><img id="myImage"></img></div>    <div class="line"><span id="text"></span></div></div><script type="text/javascript" src="cordova.js"></script><script type="text/javascript" src="js/index.js"></script></body></html>

 

 

index.js

var app = {   initialize: function() {      document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);   },   onDeviceReady: function() {      this.receivedEvent();   },   $$: function(id) {      return document.getElementById(id);   },   receivedEvent: function() {      var getDomLabrary = this.$$('openLabrary');      var _this = this;      getDomLabrary.onclick = function() {         // 打开图片库         navigator.camera.getPicture(onSuccess, onFail, {            quality: 50,                                            // 相片质量是50            sourceType: Camera.PictureSourceType.Camera,            // 设置从摄像头拍照获取            destinationType: Camera.DestinationType.FILE_URI        // 以文件路径返回         });         function onSuccess(imageURI) {             console.log(imageURI)             _this.$$('myImage').src = imageURI;             _this.$$('text').innerHTML = imageURI.substr(imageURI.lastIndexOf('/')+1);         }         function onFail(message) {            alert('Failed because: ' + message);         }      }   }};app.initialize();

 

运行:

点击按钮,打开照相机

拍照后会显示一个扣扣,点击扣扣确认拍下的照片


显示图片到页面上


 

备注:

camera插件获取了拍照的图片的文件路径并返回



 

 

续上:

通过返回的图片文件路径,获取到图片的base64编码字符串

使用这个函数就可以把图片转成base64

   // 把图片转成base64   convertImgToBase64(url, callback, outputFormat) {      var canvas = document.createElement('CANVAS'),         ctx = canvas.getContext('2d'),         img = new Image;      img.crossOrigin = 'Anonymous';      img.onload = function() {         canvas.height = img.height;         canvas.width = img.width;         ctx.drawImage(img, 0, 0);         var dataURL = canvas.toDataURL(outputFormat || 'image/png');         callback.call(this, dataURL);         canvas = null;      };      img.src = url;   }

 

index.js

var app = {   initialize: function() {      document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);   },   onDeviceReady: function() {      this.receivedEvent();   },   $$: function(id) {      return document.getElementById(id);   },   receivedEvent: function() {      var getDomLabrary = this.$$('openLabrary');      var _this = this;      getDomLabrary.onclick = function() {         // 打开图片库         navigator.camera.getPicture(onSuccess, onFail, {            quality: 50,                                            // 相片质量是50            sourceType: Camera.PictureSourceType.Camera,            // 设置摄像头拍照获取            destinationType: Camera.DestinationType.FILE_URI        // 以文件路径返回         });         function onSuccess(imageURI) {            console.log(imageURI)            _this.$$('myImage').src = imageURI;                _this.$$('text').innerHTML = imageURI.substr(imageURI.lastIndexOf('/')+1);            // 转base64            _this.convertImgToBase64(imageURI, function(base64Img) {               console.log(base64Img)            });         }         function onFail(message) {            alert('Failed because: ' + message);         }      }   },   // 把图片转成base64   convertImgToBase64(url, callback, outputFormat) {      var canvas = document.createElement('CANVAS'),         ctx = canvas.getContext('2d'),         img = new Image;      img.crossOrigin = 'Anonymous';      img.onload = function() {         canvas.height = img.height;         canvas.width = img.width;         ctx.drawImage(img, 0, 0);         var dataURL = canvas.toDataURL(outputFormat || 'image/png');         callback.call(this, dataURL);         canvas = null;      };      img.src = url;   }};app.initialize();

 

注意:

拿到的base64编码字符串是有data:image/png;base64,头部的!!!



 

 

小结:

提供以上2种方法,获取base64编码字符串。

区别:

1种方法获取的base64编码字符串没有data:image/png;base64,头部

2种方法获取的base64编码字符串有data:image/png;base64,头部

2种方法还拿到了文件名。

 

 

 

 

 

示例三:

从图库中获取图片,返回图片在系统中的路径

index.html

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8"/>        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">        <meta name="format-detection" content="telephone=no">        <meta name="msapplication-tap-highlight" content="no">        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">        <title>Hello World</title>    </head>    <body>        <div class="app">            <button id="openLabrary">按钮</button>            <img id="myImage" style="height: 200px;"></img>        </div>        <script type="text/javascript" src="cordova.js"></script>        <script type="text/javascript" src="js/index.js"></script>    </body></html>

 

 

index.js

var app = {    // Application Constructor    initialize: function() {        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);    },    // deviceready Event Handler    //    // Bind any cordova events here. Common events are:    // 'pause', 'resume', etc.    onDeviceReady: function() {        this.receivedEvent();    },    $$: function(id) {        return document.getElementById(id);    },    receivedEvent: function(){        var getDomLabrary = this.$$('openLabrary');        getDomLabrary.onclick = function(){            // 打开图片库            navigator.camera.getPicture(onSuccess, onFail, {                quality: 50,// 相片质量是50                sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM,// 设置从图片库获取                destinationType: Camera.DestinationType.FILE_URI// 以文件路径返回            });            function onSuccess(imageURI) {                 console.log(imageURI)_this.$$('myImage').src = imageURI;            }            function onFail(message) {                alert('Failed because: ' + message);            }        }    }};app.initialize();

 

运行:

点击按钮,打开图片库,选择图片,显示


 

 

 

续上:结合使用FileTransfer插件上传图片

 index.js 

var app = {    initialize: function() {        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);    },    onDeviceReady: function() {        this.receivedEvent();    },    $$: function(id) {        return document.getElementById(id);    },    receivedEvent: function(){        var getDomLabrary = this.$$('openLabrary');        var _this = this;        getDomLabrary.onclick = function(){            // 打开图片库            navigator.camera.getPicture(onSuccess, onFail, {                quality: 50,                                            // 相片质量是50                sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM,  // 设置从图片库获取                destinationType: Camera.DestinationType.FILE_URI        // 以文件路径返回            });            function onSuccess(imageURI) {                console.log(imageURI)                _this.$$('myImage').src = imageURI;                // 上传                _this.upLoadImg(imageURI);            }            function onFail(message) {                alert('Failed because: ' + message);            }        }    },    // file-Transfer插件,上传图片文件    upLoadImg(imageURI){        var options = new FileUploadOptions();        options.chunkedMode = false;        options.fileKey = "file";        options.fileName = imageURI.substring(imageURI.lastIndexOf('/')+1);        options.mimeType = "image/jpeg";        options.httpMethod = "POST";        console.log("options=======");        console.log(options);        var fileTransfer = new FileTransfer();        var successCallback = function(r){            console.log("Code = " + r.responseCode);            console.log("Response = " + r.response);            console.log("Sent = " + r.bytesSent);        }        var errorCallback = function (error) {            console.log("An error has occurred: Code = " + error.code);            console.log("upload error source " + error.source);            console.log("upload error target " + error.target);        }        fileTransfer.upload(                    imageURI,   //本地文件路径                    encodeURI("http:\/\/10.1.10.53:8089/oss/UploadServlet"),  //服务器上传的路径                    successCallback,  //成功的回调                    errorCallback,    //失败的回调                    options);         //配置项    }};app.initialize();


运行:

点击按钮,打开图片库,选择图片,显示

上传成功

 

备注:

这个上传的服务器路径:

var SERVER = "http://10.1.10.53:8089/oss/UploadServlet"

使用了一个.jsp文件写成的



需要查看fileTransfer插件的使用方法,可以点击下面链接

http://blog.csdn.net/michael_ouyang/article/details/75305119

阅读全文
0 0
原创粉丝点击