Skip to content

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.

First, add the plugin to your Cordova project via the command line:

cordova plugin add cordova-plugin-camera

Step 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;" />

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);

The core method is navigator.camera.getPicture(successCallback, errorCallback, options).

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).

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.

The options object customizes camera behavior. Key options include:

OptionConstant (if any)DescriptionDefault
qualityQuality of the saved image (0-100).50
destinationTypeCamera.DestinationTypeFormat 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
sourceTypeCamera.PictureSourceTypeSource of the picture: PHOTOLIBRARY, CAMERA, SAVEDPHOTOALBUM.CAMERA
allowEditAllow simple editing of image before selection.false
encodingTypeCamera.EncodingTypeEncoding of the returned image file: JPEG or PNG.JPEG
targetWidthScale image to this width in pixels. Maintains aspect ratio.N/A
targetHeightScale image to this height in pixels. Maintains aspect ratio.N/A
mediaTypeCamera.MediaTypeType of media to select: PICTURE, VIDEO, or ALLMEDIA.PICTURE
correctOrientationRotate the image to correct for device orientation during capture.true
saveToPhotoAlbumSave the image to the photo album on the device after capture (if sourceType is CAMERA).false
popoverOptionsCamera.PopoverOptions(iOS only) Options for iPad popover location.N/A
cameraDirectionCamera.DirectionChoose the camera to use: BACK or FRONT.BACK

Always refer to the latest cordova-plugin-camera documentation for up-to-date information and platform-specific notes.