Skip to content

Cordova - 摄像头

cordova-plugin-camera 允许您的应用使用设备的相机拍照,或从设备的照片库/相册中检索图像。

首先,通过命令行向您的 Cordova 项目添加插件:

cordova plugin add cordova-plugin-camera

步骤 2 - 添加 UI 元素(按钮和图像占位符)

Section titled “步骤 2 - 添加 UI 元素(按钮和图像占位符)”

在您的 index.html 中,添加一个按钮来触发相机,以及一个 <img> 标签来显示选择/捕获的图像。

<!-- In index.html -->
<button id="takePictureButton">Take Picture</button>
<button id="getPictureFromGalleryButton">Get Picture from Gallery</button>
<br><br>
<img id="myImagePreview" style="width:100%; max-width:300px; display:block; margin-top:10px;" />

在您的 JavaScript 文件(例如 index.js)中,在 deviceready 事件之后为按钮附加事件监听器。

// In index.js, after 'deviceready'
document.addEventListener('deviceready', () => {
document.getElementById("takePictureButton").addEventListener("click", takePicture);
document.getElementById("getPictureFromGalleryButton").addEventListener("click", getPictureFromGallery);
// Ensure Camera object is available (usually it is globally available after deviceready with the plugin)
if (!navigator.camera) {
alert("Camera API not available. Is the plugin installed correctly?");
}
}, false);

核心方法是 navigator.camera.getPicture(successCallback, errorCallback, options)。

此函数启动设备相机以捕获新照片。

function takePicture() {
if (!navigator.camera) { alert("Camera API not supported"); return; }
const options = {
quality: 75, // Quality of the saved image (0-100)
destinationType: Camera.DestinationType.DATA_URL, // Return image as base64-encoded string
// destinationType: Camera.DestinationType.FILE_URI, // Return image file URI
sourceType: Camera.PictureSourceType.CAMERA, // Use camera
encodingType: Camera.EncodingType.JPEG, // JPEG or PNG
mediaType: Camera.MediaType.PICTURE,
allowEdit: false, // Allow simple editing before selection
correctOrientation: true, // Corrects image orientation
saveToPhotoAlbum: false // Save a copy to the photo album (if sourceType is CAMERA)
// targetWidth: 1000, // Optional: Scale image to this width
// targetHeight: 1000 // Optional: Scale image to this height
};
navigator.camera.getPicture(
(imageDataOrUri) => { onSuccessShared(imageDataOrUri, options.destinationType); },
onFail,
options
);
}
function onFail(message) {
alert('Failed because: ' + message);
console.error('Camera failed: ' + message);
}

按下 TAKE PICTURE 时,将打开原生相机 UI。拍照并确认后,会调用 onSuccessShared。如果 destinationType 是 DATA_URL,图像会直接显示。如果 FILE_URI,则将 src 设置为文件路径(可能需要 cdvfile: 的 CSP 配置)。

B. 从相册获取图片 (getPictureFromGallery)

Section titled “B. 从相册获取图片 (getPictureFromGallery)”

此函数打开设备的照片库供用户选择现有图像。

function getPictureFromGallery() {
if (!navigator.camera) { alert("Camera API not supported"); return; }
const galleryOptions = {
quality: 75,
destinationType: Camera.DestinationType.FILE_URI, // FILE_URI is often preferred for gallery images
// destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY, // Or SAVEDPHOTOALBUM
encodingType: Camera.EncodingType.JPEG,
mediaType: Camera.MediaType.PICTURE,
correctOrientation: true
// targetWidth: 1000,
// targetHeight: 1000
};
navigator.camera.getPicture(
(imageDataOrUri) => { onSuccessShared(imageDataOrUri, galleryOptions.destinationType); },
onFail,
galleryOptions
);
}
// Shared success handler example (can be defined once and used by both takePicture and getPictureFromGallery)
function onSuccessShared(imageDataOrUri, destinationType) {
const imagePreview = document.getElementById('myImagePreview');
if (destinationType === Camera.DestinationType.DATA_URL) {
imagePreview.src = "data:image/jpeg;base64," + imageDataOrUri;
} else {
imagePreview.src = imageDataOrUri; // Ensure CSP allows cdvfile: for img src
// For Ionic WebView, you might use: imagePreview.src = window.Ionic.WebView.convertFileSrc(imageDataOrUri);
}
console.log("Image selected/captured successfully.");
}
// `onFail` can be reused from the takePicture example.

按下 GET PICTURE FROM GALLERY 将打开图像库。选择后,图像会显示出来。

options 对象用于自定义相机行为。主要选项包括:

选项常量(如有)描述默认值
quality保存的图像质量(0-100)。50
destinationTypeCamera.DestinationType返回值格式:DATA_URL (Base64 字符串),FILE_URI (文件路径),NATIVE_URI (平台特定的原生路径,例如 iOS 上的 assets-library:// 或 Android 上的 content://)。FILE_URI
sourceTypeCamera.PictureSourceType图片来源:PHOTOLIBRARY,CAMERA,SAVEDPHOTOALBUM。CAMERA
allowEdit允许在选择前对图像进行简单编辑。false
encodingTypeCamera.EncodingType返回的图像文件编码:JPEG 或 PNG。JPEG
targetWidth将图像缩放到此宽度(像素)。保持宽高比。N/A
targetHeight将图像缩放到此高度(像素)。保持宽高比。N/A
mediaTypeCamera.MediaType选择的媒体类型:PICTURE,VIDEO 或 ALLMEDIA。PICTURE
correctOrientation在捕获过程中旋转图像以校正设备方向。true
saveToPhotoAlbum捕获后(如果 sourceType 是 CAMERA)将图像保存到设备相册。false
popoverOptionsCamera.PopoverOptions(仅限 iOS)iPad 弹窗位置选项。N/A
cameraDirectionCamera.Direction选择要使用的相机:BACK(后置)或 FRONT(前置)。BACK

请始终参考最新的 cordova-plugin-camera 文档以获取最新信息和平台特定说明。