Cordova - Camera
Cordova - Camera
Section titled “Cordova - Camera”The cordova-plugin-camera allows your application to take photos using the device’s camera or retrieve images from the device’s photo library/gallery.
Step 1 - Install the Camera Plugin
Section titled “Step 1 - Install the Camera Plugin”First, add the plugin to your Cordova project via the command line:
cordova plugin add cordova-plugin-cameraStep 2 - Adding UI Elements (Button and Image Placeholder)
Section titled “Step 2 - Adding UI Elements (Button and Image Placeholder)”In your index.html, add a button to trigger the camera and an <img> tag to display the selected/captured image.
<!-- 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;" />Step 3 - Adding Event Listeners
Section titled “Step 3 - Adding Event Listeners”In your JavaScript file (e.g., index.js), attach event listeners to the buttons after the deviceready event.
// 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);Step 4 - Implementing Camera Functions
Section titled “Step 4 - Implementing Camera Functions”The core method is navigator.camera.getPicture(successCallback, errorCallback, options).
A. Taking a Picture (takePicture)
Section titled “A. Taking a Picture (takePicture)”This function launches the device camera to capture a new photo.
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);}When TAKE PICTURE is pressed, the native camera UI opens. After taking and confirming the photo, onSuccessShared is called. If destinationType is DATA_URL, the image is displayed directly. If FILE_URI, the src is set to the file path (CSP for cdvfile: might be needed).
B. Getting Picture from Gallery (getPictureFromGallery)
Section titled “B. Getting Picture from Gallery (getPictureFromGallery)”This function opens the device’s photo gallery for the user to select an existing image.
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.Pressing GET PICTURE FROM GALLERY opens the image library. After selection, the image is displayed.
Camera Options (Camera.options)
Section titled “Camera Options (Camera.options)”The options object customizes camera behavior. Key options include:
| Option | Constant (if any) | Description | Default |
|---|---|---|---|
| quality | Quality of the saved image (0-100). | 50 | |
| destinationType | Camera.DestinationType | Format of the return value: DATA_URL (Base64 string), FILE_URI (file path), NATIVE_URI (platform-specific native path, e.g., assets-library:// on iOS or content:// on Android). | FILE_URI |
| sourceType | Camera.PictureSourceType | Source of the picture: PHOTOLIBRARY, CAMERA, SAVEDPHOTOALBUM. | CAMERA |
| allowEdit | Allow simple editing of image before selection. | false | |
| encodingType | Camera.EncodingType | Encoding of the returned image file: JPEG or PNG. | JPEG |
| targetWidth | Scale image to this width in pixels. Maintains aspect ratio. | N/A | |
| targetHeight | Scale image to this height in pixels. Maintains aspect ratio. | N/A | |
| mediaType | Camera.MediaType | Type of media to select: PICTURE, VIDEO, or ALLMEDIA. | PICTURE |
| correctOrientation | Rotate the image to correct for device orientation during capture. | true | |
| saveToPhotoAlbum | Save the image to the photo album on the device after capture (if sourceType is CAMERA). | false | |
| popoverOptions | Camera.PopoverOptions | (iOS only) Options for iPad popover location. | N/A |
| cameraDirection | Camera.Direction | Choose the camera to use: BACK or FRONT. | BACK |
Important Considerations
Section titled “Important Considerations”Always refer to the latest cordova-plugin-camera documentation for up-to-date information and platform-specific notes.