Cordova - 摄像头
Cordova - 相机
Section titled “Cordova - 相机”cordova-plugin-camera 允许您的应用使用设备的相机拍照,或从设备的照片库/相册中检索图像。
步骤 1 - 安装相机插件
Section titled “步骤 1 - 安装相机插件”首先,通过命令行向您的 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;" />步骤 3 - 添加事件监听器
Section titled “步骤 3 - 添加事件监听器”在您的 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);步骤 4 - 实现相机功能
Section titled “步骤 4 - 实现相机功能”核心方法是 navigator.camera.getPicture(successCallback, errorCallback, options)。
A. 拍照 (takePicture)
Section titled “A. 拍照 (takePicture)”此函数启动设备相机以捕获新照片。
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 将打开图像库。选择后,图像会显示出来。
相机选项 (Camera.options)
Section titled “相机选项 (Camera.options)”options 对象用于自定义相机行为。主要选项包括:
| 选项 | 常量(如有) | 描述 | 默认值 |
|---|---|---|---|
| quality | 保存的图像质量(0-100)。 | 50 | |
| destinationType | Camera.DestinationType | 返回值格式:DATA_URL (Base64 字符串),FILE_URI (文件路径),NATIVE_URI (平台特定的原生路径,例如 iOS 上的 assets-library:// 或 Android 上的 content://)。 | FILE_URI |
| sourceType | Camera.PictureSourceType | 图片来源:PHOTOLIBRARY,CAMERA,SAVEDPHOTOALBUM。 | CAMERA |
| allowEdit | 允许在选择前对图像进行简单编辑。 | false | |
| encodingType | Camera.EncodingType | 返回的图像文件编码:JPEG 或 PNG。 | JPEG |
| targetWidth | 将图像缩放到此宽度(像素)。保持宽高比。 | N/A | |
| targetHeight | 将图像缩放到此高度(像素)。保持宽高比。 | N/A | |
| mediaType | Camera.MediaType | 选择的媒体类型:PICTURE,VIDEO 或 ALLMEDIA。 | PICTURE |
| correctOrientation | 在捕获过程中旋转图像以校正设备方向。 | true | |
| saveToPhotoAlbum | 捕获后(如果 sourceType 是 CAMERA)将图像保存到设备相册。 | false | |
| popoverOptions | Camera.PopoverOptions | (仅限 iOS)iPad 弹窗位置选项。 | N/A |
| cameraDirection | Camera.Direction | 选择要使用的相机:BACK(后置)或 FRONT(前置)。 | BACK |
重要注意事项
Section titled “重要注意事项”请始终参考最新的 cordova-plugin-camera 文档以获取最新信息和平台特定说明。