介绍
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/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.CAMERA和Camera.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的类型,如果destinationType是DATA_URI,则该参数返回Base64编码的图片数据;如果destinationType的FIEL_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 | number | 50 | 图像的保存质量,范围0-100,100是最大值,最高的分辨率,没有任何压缩损失(请注意有关该相机的分辨率信息不可用。) |
destinationType | DestinationType | FILE_URI | 选择返回值的格式 |
sourceType | PictureSourceType | CAMERA | 获取图片的来 |
allowEdit | Boolean | true | 允许在选择图片之前进行简单的编辑 |
encodingType | EncodingType | JPEG | 选择图像的返回编码 |
targetWidth | number | 宽度像素用来缩放图像。必须和targetHeight一起使用。宽高比保持不变。 | |
targetHeight | number | 高度像素用来缩放图像。必须和targetWidth一起使用。宽高比保持不变 | |
mediaType | MediaType | PICTURE | 选择media类型。它只适用PictureSourceType是PHOTOLIBRARY或SAVEDPHOTOALBUM |
correctOrientation | Boolean | 如果是横向拍摄的照片,会自动旋转到正确的方向 | |
saveToPhotoAlbum | Boolean | 设备拍照后的图像是否保存的图片库中 | |
popoverOptions | CameraPopoverOptions | 仅ios可用,设定在ipad的popover的位置 | |
cameraDirection | Direction | BACK | 选择前置摄像头还是后置摄像头 |
变量名 | 类型 | 默认值 | 描述 |
DATA_URL | number | 0 | 返回Base64编码的字符串 |
FILE_URI | number | 1 | 返回文件的URI(content://media/external/images/media/2 for Android) |
NATIVE_URI | number | 2 | 返回原生URI (eg. asset-library://... for iOS) |
变量名 | 类型 | 默认值 | 描述 |
JPEG | number | 0 | 返回JPEG的图片 |
PNG | number | 1 | 返回PNG的图片 |
Camera.MediaType :枚举 类型:相机的静态枚举属性 特性:
变量名 | 类型 | 默认值 | 描述 |
PICTURE | number | 0 | 仅允许选择静态影像。 默认。将通过DestinationType返回指定格式 |
VIDEO | number | 1 | 仅允许选择视频,只返回网址 |
ALLMEDIA | number | 2 | 允许返回所有媒体格式 |
Camera.PictureSourceType :枚举 类型:相机的静态枚举属性 特性:
变量名 | 类型 | 默认值 | 描述 |
PHOTOLIBRARY | number | 0 | 从设备相册选择图片 |
CAMERA | number | 1 | 用摄像头拍摄图片 |
SAVEDPHOTOALBUM | number | 2 | 从设备相册选择图片(一个应该是ios一个安卓) |
Camera.PopoverArrowDirection :枚举 匹配的iOS UIPopoverArrowDirection在popover固定的箭头位置。 类型:相机的静态枚举属性 特性:
变量名 | 类型 | 默认值 |
ARROW_UP | number | 1 |
ARROW_DOWN | number | 2 |
ARROW_LEFT | number | 4 |
ARROW_RIGHT | number | 8 |
ARROW_ANY | number | 15 |
Camera.Direction :enum 类型:相机的静态枚举属性 特性:
变量名 | 类型 | 默认值 | 描述 |
BACK | number | 0 | 使用后置摄像头 |
FRONT | number | 1 | 使用前置摄像头 |
CameraPopoverOptions iOS特供,从iPad的系统相册选择图片,指定popover的定位元素的位置箭头方向和参数。需要注意的是popover的尺寸可以改变,以适应屏幕的箭头和取向方向。确保指定元素位置时考虑方向变化。
变量名 | 类型 | 默认值 | 描述 |
[x] | number | 0 | 屏幕选取框的x坐标 |
[y] | number | 32 | 屏幕选取框的y坐标 |
[width] | number | 320 | 屏幕选取框的宽度 |
[height] | number | 480 | 屏幕选取框的高度 |
[arrowDir] | PopoverArrowDirection | ARROW_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 '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 '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 '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/michael_ouyang/article/details/75305119
更多推荐
cordova camera插件——摄像头插件的使用及上传图片
发布评论