Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cordova-plugin-camera

Package Overview
Dependencies
Maintainers
1
Versions
39
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cordova-plugin-camera

Cordova Camera Plugin

  • 2.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
17K
decreased by-2.55%
Maintainers
1
Weekly downloads
 
Created
Source

cordova-plugin-camera

This plugin defines a global navigator.camera object, which provides an API for taking pictures and for choosing images from the system's image library.

Although the object is attached to the global scoped navigator, it is not available until after the deviceready event.

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    console.log(navigator.camera);
}

Installation

This requires cordova 5.0+

cordova plugin add cordova-plugin-camera

Older versions of cordova can still install via the deprecated id

cordova plugin add org.apache.cordova.camera

It is also possible to install via repo url directly ( unstable )

cordova plugin add https://github.com/apache/cordova-plugin-camera.git

How to Contribute

Contributors are welcome! And we need your contributions to keep the project moving forward. You can report bugs, improve the documentation, or contribute code.

There is a specific contributor workflow we recommend. Start reading there. More information is available on our wiki.

:warning: Found an issue? File it on JIRA issue tracker.

Have a solution? Send a Pull Request.

In order for your changes to be accepted, you need to sign and submit an Apache ICLA (Individual Contributor License Agreement). Then your name will appear on the list of CLAs signed by non-committers or Cordova committers.

And don't forget to test and document your code.

This documentation is generated by a tool

:warning: Run npm install in the plugin repo to enable automatic docs generation if you plan to send a PR.
jsdoc-to-markdown is used to generate the docs.
Documentation consists of template and API docs produced from the plugin JS code and should be regenerated before each commit (done automatically via husky, running npm run gen-docs script as a precommit hook - see package.json for details).


API Reference


camera

camera.getPicture(successCallback, errorCallback, options)

Takes a photo using the camera, or retrieves a photo from the device's image gallery. The image is passed to the success callback as a base64-encoded String, or as the URI for the image file.

The camera.getPicture function opens the device's default camera application that allows users to snap pictures by default - this behavior occurs, when Camera.sourceType equals Camera.PictureSourceType.CAMERA.
Once the user snaps the photo, the camera application closes and the application is restored.

If Camera.sourceType is Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a dialog displays that allows users to select an existing image. The camera.getPicture function returns a CameraPopoverHandle object, which can be used to reposition the image selection dialog, for example, when the device orientation changes.

The return value is sent to the cameraSuccess callback function, in one of the following formats, depending on the specified cameraOptions:

  • A String containing the base64-encoded photo image.

  • A String representing the image file location on local storage (default).

You can do whatever you want with the encoded image or URI, for example:

  • Render the image in an <img> tag, as in the example below

  • Save the data locally (LocalStorage, Lawnchair, etc.)

  • Post the data to a remote server

NOTE: Photo resolution on newer devices is quite good. Photos selected from the device's gallery are not downscaled to a lower quality, even if a quality parameter is specified. To avoid common memory problems, set Camera.destinationType to FILE_URI rather than DATA_URL.

Supported Platforms

Kind: static method of camera

ParamTypeDescription
successCallbackonSuccess
errorCallbackonError
optionsCameraOptionsCameraOptions

Example

navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);

camera.cleanup()

Removes intermediate image files that are kept in temporary storage after calling camera.getPicture. Applies only when the value of Camera.sourceType equals Camera.PictureSourceType.CAMERA and the Camera.destinationType equals Camera.DestinationType.FILE_URI.

Supported Platforms

Kind: static method of camera
Example

navigator.camera.cleanup(onSuccess, onFail);

function onSuccess() {
    console.log("Camera cleanup success.")
}

function onFail(message) {
    alert('Failed because: ' + message);
}

camera.onError : function

Callback function that provides an error message.

Kind: static typedef of camera

ParamTypeDescription
messagestringThe message is provided by the device's native code.

camera.onSuccess : function

Callback function that provides the image data.

Kind: static typedef of camera

ParamTypeDescription
imageDatastringBase64 encoding of the image data, or the image file URI, depending on cameraOptions in effect.

Example

// Show image
//
function cameraCallback(imageData) {
   var image = document.getElementById('myImage');
   image.src = "data:image/jpeg;base64," + imageData;
}

camera.CameraOptions : Object

Optional parameters to customize the camera settings.

Kind: static typedef of camera
Properties

NameTypeDefaultDescription
qualitynumber50Quality of the saved image, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information about the camera's resolution is unavailable.)
destinationTypeDestinationTypeFILE_URIChoose the format of the return value.
sourceTypePictureSourceTypeCAMERASet the source of the picture.
allowEditBooleantrueAllow simple editing of image before selection.
encodingTypeEncodingTypeJPEGChoose the returned image file's encoding.
targetWidthnumberWidth in pixels to scale image. Must be used with targetHeight. Aspect ratio remains constant.
targetHeightnumberHeight in pixels to scale image. Must be used with targetWidth. Aspect ratio remains constant.
mediaTypeMediaTypePICTURESet the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM.
correctOrientationBooleanRotate the image to correct for the orientation of the device during capture.
saveToPhotoAlbumBooleanSave the image to the photo album on the device after capture.
popoverOptionsCameraPopoverOptionsiOS-only options that specify popover location in iPad.
cameraDirectionDirectionBACKChoose the camera to use (front- or back-facing).

Camera

Camera.DestinationType : enum

Kind: static enum property of Camera
Properties

NameTypeDefaultDescription
DATA_URLnumber0Return base64 encoded string
FILE_URInumber1Return file uri (content://media/external/images/media/2 for Android)
NATIVE_URInumber2Return native uri (eg. asset-library://... for iOS)

Camera.EncodingType : enum

Kind: static enum property of Camera
Properties

NameTypeDefaultDescription
JPEGnumber0Return JPEG encoded image
PNGnumber1Return PNG encoded image

Camera.MediaType : enum

Kind: static enum property of Camera
Properties

NameTypeDefaultDescription
PICTUREnumber0Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEOnumber1Allow selection of video only, ONLY RETURNS URL
ALLMEDIAnumber2Allow selection from all media types

Camera.PictureSourceType : enum

Kind: static enum property of Camera
Properties

NameTypeDefaultDescription
PHOTOLIBRARYnumber0Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
CAMERAnumber1Take picture from camera
SAVEDPHOTOALBUMnumber2Choose image from picture library (same as PHOTOLIBRARY for Android)

Camera.PopoverArrowDirection : enum

Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.

Kind: static enum property of Camera
Properties

NameTypeDefault
ARROW_UPnumber1
ARROW_DOWNnumber2
ARROW_LEFTnumber4
ARROW_RIGHTnumber8
ARROW_ANYnumber15

Camera.Direction : enum

Kind: static enum property of Camera
Properties

NameTypeDefaultDescription
BACKnumber0Use the back-facing camera
FRONTnumber1Use the front-facing camera

CameraPopoverOptions

iOS-only parameters that specify the anchor element location and arrow direction of the popover when selecting images from an iPad's library or album. Note that the size of the popover may change to adjust to the direction of the arrow and orientation of the screen. Make sure to account for orientation changes when specifying the anchor element location.

ParamTypeDefaultDescription
[x]Number0x pixel coordinate of screen element onto which to anchor the popover.
[y]Number32y pixel coordinate of screen element onto which to anchor the popover.
[width]Number320width, in pixels, of the screen element onto which to anchor the popover.
[height]Number480height, in pixels, of the screen element onto which to anchor the popover.
[arrowDir]PopoverArrowDirectionARROW_ANYDirection the arrow on the popover should point.

CameraPopoverHandle

A handle to an image picker popover.

Supported Platforms

Example

var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ 
    destinationType: Camera.DestinationType.FILE_URI,
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
    popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});

// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
    var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
    cameraPopoverHandle.setPosition(cameraPopoverOptions);
}

camera.getPicture Errata

Example

Take a photo and retrieve it as a base64-encoded image:

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

Take a photo and retrieve the image's file location:

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);
}
Preferences (iOS)
  • CameraUsesGeolocation (boolean, defaults to false). For capturing JPEGs, set to true to get geolocation data in the EXIF header. This will trigger a request for geolocation permissions if set to true.

     <preference name="CameraUsesGeolocation" value="false" />
    
Amazon Fire OS Quirks

Amazon Fire OS uses intents to launch the camera activity on the device to capture images, and on phones with low memory, the Cordova activity may be killed. In this scenario, the image may not appear when the cordova activity is restored.

Android Quirks

Android uses intents to launch the camera activity on the device to capture images, and on phones with low memory, the Cordova activity may be killed. In this scenario, the result from the plugin call will be delivered via the resume event. See the Android Lifecycle guide for more information. The pendingResult.result value will contain the value that would be passed to the callbacks (either the URI/URL or an error message). Check the pendingResult.pluginStatus to determine whether or not the call was successful.

Browser Quirks

Can only return photos as base64-encoded image.

Firefox OS Quirks

Camera plugin is currently implemented using Web Activities.

iOS Quirks

Including a JavaScript alert() in either of the callback functions can cause problems. Wrap the alert within a setTimeout() to allow the iOS image picker or popover to fully close before the alert displays:

setTimeout(function() {
    // do your thing here!
}, 0);
Windows Phone 7 Quirks

Invoking the native camera application while the device is connected via Zune does not work, and triggers an error callback.

Tizen Quirks

Tizen only supports a destinationType of Camera.DestinationType.FILE_URI and a sourceType of Camera.PictureSourceType.PHOTOLIBRARY.

CameraOptions Errata

Amazon Fire OS Quirks
  • Any cameraDirection value results in a back-facing photo.

  • Ignores the allowEdit parameter.

  • Camera.PictureSourceType.PHOTOLIBRARY and Camera.PictureSourceType.SAVEDPHOTOALBUM both display the same photo album.

Android Quirks
  • Any cameraDirection value results in a back-facing photo.

  • allowEdit is unpredictable on Android and it should not be used! The Android implementation of this plugin tries to find and use an application on the user's device to do image cropping. The plugin has no control over what application the user selects to perform the image cropping and it is very possible that the user could choose an incompatible option and cause the plugin to fail. This sometimes works because most devices come with an application that handles cropping in a way that is compatible with this plugin (Google Plus Photos), but it is unwise to rely on that being the case. If image editing is essential to your application, consider seeking a third party library or plugin that provides its own image editing utility for a more robust solution.

  • Camera.PictureSourceType.PHOTOLIBRARY and Camera.PictureSourceType.SAVEDPHOTOALBUM both display the same photo album.

  • Ignores the encodingType parameter if the image is unedited (i.e. quality is 100, correctOrientation is false, and no targetHeight or targetWidth are specified). The CAMERA source will always return the JPEG file given by the native camera and the PHOTOLIBRARY and SAVEDPHOTOALBUM sources will return the selected file in its existing encoding.

BlackBerry 10 Quirks
  • Ignores the quality parameter.

  • Ignores the allowEdit parameter.

  • Camera.MediaType is not supported.

  • Ignores the correctOrientation parameter.

  • Ignores the cameraDirection parameter.

Firefox OS Quirks
  • Ignores the quality parameter.

  • Camera.DestinationType is ignored and equals 1 (image file URI)

  • Ignores the allowEdit parameter.

  • Ignores the PictureSourceType parameter (user chooses it in a dialog window)

  • Ignores the encodingType

  • Ignores the targetWidth and targetHeight

  • Camera.MediaType is not supported.

  • Ignores the correctOrientation parameter.

  • Ignores the cameraDirection parameter.

iOS Quirks
  • When using destinationType.FILE_URI, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends.

  • When using destinationType.NATIVE_URI and sourceType.CAMERA, photos are saved in the saved photo album regardless on the value of saveToPhotoAlbum parameter.

Tizen Quirks
  • options not supported

  • always returns a FILE URI

Windows Phone 7 and 8 Quirks
  • Ignores the allowEdit parameter.

  • Ignores the correctOrientation parameter.

  • Ignores the cameraDirection parameter.

  • Ignores the saveToPhotoAlbum parameter. IMPORTANT: All images taken with the wp7/8 cordova camera API are always copied to the phone's camera roll. Depending on the user's settings, this could also mean the image is auto-uploaded to their OneDrive. This could potentially mean the image is available to a wider audience than your app intended. If this a blocker for your application, you will need to implement the CameraCaptureTask as documented on msdn : http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx You may also comment or up-vote the related issue in the issue tracker

  • Ignores the mediaType property of cameraOptions as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.

Keywords

FAQs

Package last updated on 20 Jan 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc