UNPKG

19.8 kBMarkdownView Raw
1---
2title: Camera
3description: Take pictures with the device camera.
4---
5{{>cdv-license~}}
6
7|Android|iOS| Windows 8.1 Store | Windows 8.1 Phone | Windows 10 Store | Travis CI |
8|:-:|:-:|:-:|:-:|:-:|:-:|
9|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-camera)
10
11# cordova-plugin-camera
12
13This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from
14the system's image library.
15
16{{>cdv-header device-ready-warning-obj='navigator.camera' npmName='cordova-plugin-camera' cprName='org.apache.cordova.camera' pluginName='Plugin Camera' repoUrl='https://github.com/apache/cordova-plugin-camera' }}
17
18
19### iOS Quirks
20
21Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist.
22
23- `NSCameraUsageDescription` describes the reason that the app accesses the user’s camera.
24- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library.
25
26When the system prompts the user to allow access, this string is displayed as part of the dialog box.
27
28To add this entry you can pass the following variables on plugin install.
29
30- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription`
31- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription`
32
33Example:
34
35 cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
36
37If you don't pass the variable, the plugin will add an empty string as value.
38
39---
40
41# API Reference <a name="reference"></a>
42
43{{#orphans~}}
44{{>member-index}}
45{{/orphans}}
46* [CameraPopoverHandle](#module_CameraPopoverHandle)
47* [CameraPopoverOptions](#module_CameraPopoverOptions)
48
49---
50
51{{#modules~}}
52{{>header~}}
53{{>body~}}
54{{>members~}}
55
56---
57
58{{/modules}}
59
60## `camera.getPicture` Errata
61
62#### Example <a name="camera-getPicture-examples"></a>
63
64Take a photo and retrieve the image's file location:
65
66 navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
67 destinationType: Camera.DestinationType.FILE_URI });
68
69 function onSuccess(imageURI) {
70 var image = document.getElementById('myImage');
71 image.src = imageURI;
72 }
73
74 function onFail(message) {
75 alert('Failed because: ' + message);
76 }
77
78Take a photo and retrieve it as a Base64-encoded image:
79
80 /**
81 * Warning: Using DATA_URL is not recommended! The DATA_URL destination
82 * type is very memory intensive, even with a low quality setting. Using it
83 * can result in out of memory errors and application crashes. Use FILE_URI
84 * or NATIVE_URI instead.
85 */
86 navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
87 destinationType: Camera.DestinationType.DATA_URL
88 });
89
90 function onSuccess(imageData) {
91 var image = document.getElementById('myImage');
92 image.src = "data:image/jpeg;base64," + imageData;
93 }
94
95 function onFail(message) {
96 alert('Failed because: ' + message);
97 }
98
99#### Preferences (iOS)
100
101- __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.
102
103 <preference name="CameraUsesGeolocation" value="false" />
104
105#### Amazon Fire OS Quirks <a name="camera-getPicture-quirks"></a>
106
107Amazon Fire OS uses intents to launch the camera activity on the device to capture
108images, and on phones with low memory, the Cordova activity may be killed. In this
109scenario, the image may not appear when the Cordova activity is restored.
110
111#### Android Quirks
112
113Android uses intents to launch the camera activity on the device to capture
114images, and on phones with low memory, the Cordova activity may be killed. In this
115scenario, the result from the plugin call will be delivered via the resume event.
116See [the Android Lifecycle guide][android_lifecycle]
117for more information. The `pendingResult.result` value will contain the value that
118would be passed to the callbacks (either the URI/URL or an error message). Check
119the `pendingResult.pluginStatus` to determine whether or not the call was
120successful.
121
122#### Browser Quirks
123
124Can only return photos as Base64-encoded image.
125
126#### Firefox OS Quirks
127
128Camera plugin is currently implemented using [Web Activities][web_activities].
129
130#### iOS Quirks
131
132Including a JavaScript `alert()` in either of the callback functions
133can cause problems. Wrap the alert within a `setTimeout()` to allow
134the iOS image picker or popover to fully close before the alert
135displays:
136
137 setTimeout(function() {
138 // do your thing here!
139 }, 0);
140
141#### Windows Phone 7 Quirks
142
143Invoking the native camera application while the device is connected
144via Zune does not work, and triggers an error callback.
145
146#### Windows quirks
147
148On Windows Phone 8.1 using `SAVEDPHOTOALBUM` or `PHOTOLIBRARY` as a source type causes application to suspend until file picker returns the selected image and
149then restore with start page as defined in app's `config.xml`. In case when `camera.getPicture` was called from different page, this will lead to reloading
150start page from scratch and success and error callbacks will never be called.
151
152To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page.
153
154More information about Windows Phone 8.1 picker APIs is here: [How to continue your Windows Phone app after calling a file picker](https://msdn.microsoft.com/en-us/library/windows/apps/dn720490.aspx)
155
156#### Tizen Quirks
157
158Tizen only supports a `destinationType` of
159`Camera.DestinationType.FILE_URI` and a `sourceType` of
160`Camera.PictureSourceType.PHOTOLIBRARY`.
161
162
163## `CameraOptions` Errata <a name="CameraOptions-quirks"></a>
164
165#### Amazon Fire OS Quirks
166
167- Any `cameraDirection` value results in a back-facing photo.
168
169- Ignores the `allowEdit` parameter.
170
171- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
172
173#### Android Quirks
174
175- Any `cameraDirection` value results in a back-facing photo.
176
177- **`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.
178
179- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
180
181- 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.
182
183#### BlackBerry 10 Quirks
184
185- Ignores the `quality` parameter.
186
187- Ignores the `allowEdit` parameter.
188
189- `Camera.MediaType` is not supported.
190
191- Ignores the `correctOrientation` parameter.
192
193- Ignores the `cameraDirection` parameter.
194
195#### Firefox OS Quirks
196
197- Ignores the `quality` parameter.
198
199- `Camera.DestinationType` is ignored and equals `1` (image file URI)
200
201- Ignores the `allowEdit` parameter.
202
203- Ignores the `PictureSourceType` parameter (user chooses it in a dialog window)
204
205- Ignores the `encodingType`
206
207- Ignores the `targetWidth` and `targetHeight`
208
209- `Camera.MediaType` is not supported.
210
211- Ignores the `correctOrientation` parameter.
212
213- Ignores the `cameraDirection` parameter.
214
215#### iOS Quirks
216
217- 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.
218
219- When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter.
220
221- When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture.
222
223#### Tizen Quirks
224
225- options not supported
226
227- always returns a FILE URI
228
229#### Windows Phone 7 and 8 Quirks
230
231- Ignores the `allowEdit` parameter.
232
233- Ignores the `correctOrientation` parameter.
234
235- Ignores the `cameraDirection` parameter.
236
237- Ignores the `saveToPhotoAlbum` parameter. IMPORTANT: All images taken with the WP8/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 is a blocker for your application, you will need to implement the CameraCaptureTask as [documented on MSDN][msdn_wp8_docs]. You may also comment or up-vote the related issue in the [issue tracker][wp8_bug].
238
239- Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.
240
241[android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html
242[web_activities]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
243[wp8_bug]: https://issues.apache.org/jira/browse/CB-2083
244[msdn_wp8_docs]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx
245
246## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails <a name="sample"></a>
247
248The Camera plugin allows you to do things like open the device's Camera app and take a picture, or open the file picker and select one. The code snippets in this section demonstrate different tasks including:
249
250* Open the Camera app and [take a Picture](#takePicture)
251* Take a picture and [return thumbnails](#getThumbnails) (resized picture)
252* Take a picture and [generate a FileEntry object](#convert)
253* [Select a file](#selectFile) from the picture library
254* Select a JPEG image and [return thumbnails](#getFileThumbnails) (resized image)
255* Select an image and [generate a FileEntry object](#convert)
256
257## Take a Picture <a name="takePicture"></a>
258
259Before you can take a picture, you need to set some Camera plugin options to pass into the Camera plugin's `getPicture` function. Here is a common set of recommendations. In this example, you create the object that you will use for the Camera options, and set the `sourceType` dynamically to support both the Camera app and the file picker.
260
261```js
262function setOptions(srcType) {
263 var options = {
264 // Some common settings are 20, 50, and 100
265 quality: 50,
266 destinationType: Camera.DestinationType.FILE_URI,
267 // In this app, dynamically set the picture source, Camera or photo gallery
268 sourceType: srcType,
269 encodingType: Camera.EncodingType.JPEG,
270 mediaType: Camera.MediaType.PICTURE,
271 allowEdit: true,
272 correctOrientation: true //Corrects Android orientation quirks
273 }
274 return options;
275}
276```
277
278Typically, you want to use a FILE_URI instead of a DATA_URL to avoid most memory issues. JPEG is the recommended encoding type for Android.
279
280You take a picture by passing in the options object to `getPicture`, which takes a CameraOptions object as the third argument. When you call `setOptions`, pass `Camera.PictureSourceType.CAMERA` as the picture source.
281
282```js
283function openCamera(selection) {
284
285 var srcType = Camera.PictureSourceType.CAMERA;
286 var options = setOptions(srcType);
287 var func = createNewFileEntry;
288
289 navigator.camera.getPicture(function cameraSuccess(imageUri) {
290
291 displayImage(imageUri);
292 // You may choose to copy the picture, save it somewhere, or upload.
293 func(imageUri);
294
295 }, function cameraError(error) {
296 console.debug("Unable to obtain picture: " + error, "app");
297
298 }, options);
299}
300```
301
302Once you take the picture, you can display it or do something else. In this example, call the app's `displayImage` function from the preceding code.
303
304```js
305function displayImage(imgUri) {
306
307 var elem = document.getElementById('imageFile');
308 elem.src = imgUri;
309}
310```
311
312To display the image on some platforms, you might need to include the main part of the URI in the Content-Security-Policy `<meta>` element in index.html. For example, on Windows 10, you can include `ms-appdata:` in your `<meta>` element. Here is an example.
313
314```html
315<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: ms-appdata: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
316```
317
318## Take a Picture and Return Thumbnails (Resize the Picture) <a name="getThumbnails"></a>
319
320To get smaller images, you can return a resized image by passing both `targetHeight` and `targetWidth` values with your CameraOptions object. In this example, you resize the returned image to fit in a 100px by 100px box (the aspect ratio is maintained, so 100px is either the height or width, whichever is greater in the source).
321
322```js
323function openCamera(selection) {
324
325 var srcType = Camera.PictureSourceType.CAMERA;
326 var options = setOptions(srcType);
327 var func = createNewFileEntry;
328
329 if (selection == "camera-thmb") {
330 options.targetHeight = 100;
331 options.targetWidth = 100;
332 }
333
334 navigator.camera.getPicture(function cameraSuccess(imageUri) {
335
336 // Do something
337
338 }, function cameraError(error) {
339 console.debug("Unable to obtain picture: " + error, "app");
340
341 }, options);
342}
343```
344
345## Select a File from the Picture Library <a name="selectFile"></a>
346
347When selecting a file using the file picker, you also need to set the CameraOptions object. In this example, set the `sourceType` to `Camera.PictureSourceType.SAVEDPHOTOALBUM`. To open the file picker, call `getPicture` just as you did in the previous example, passing in the success and error callbacks along with CameraOptions object.
348
349```js
350function openFilePicker(selection) {
351
352 var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
353 var options = setOptions(srcType);
354 var func = createNewFileEntry;
355
356 navigator.camera.getPicture(function cameraSuccess(imageUri) {
357
358 // Do something
359
360 }, function cameraError(error) {
361 console.debug("Unable to obtain picture: " + error, "app");
362
363 }, options);
364}
365```
366
367## Select an Image and Return Thumbnails (resized images) <a name="getFileThumbnails"></a>
368
369Resizing a file selected with the file picker works just like resizing using the Camera app; set the `targetHeight` and `targetWidth` options.
370
371```js
372function openFilePicker(selection) {
373
374 var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
375 var options = setOptions(srcType);
376 var func = createNewFileEntry;
377
378 if (selection == "picker-thmb") {
379 // To downscale a selected image,
380 // Camera.EncodingType (e.g., JPEG) must match the selected image type.
381 options.targetHeight = 100;
382 options.targetWidth = 100;
383 }
384
385 navigator.camera.getPicture(function cameraSuccess(imageUri) {
386
387 // Do something with image
388
389 }, function cameraError(error) {
390 console.debug("Unable to obtain picture: " + error, "app");
391
392 }, options);
393}
394```
395
396## Take a picture and get a FileEntry Object <a name="convert"></a>
397
398If you want to do something like copy the image to another location, or upload it somewhere using the FileTransfer plugin, you need to get a FileEntry object for the returned picture. To do that, call `window.resolveLocalFileSystemURL` on the file URI returned by the Camera app. If you need to use a FileEntry object, set the `destinationType` to `Camera.DestinationType.FILE_URI` in your CameraOptions object (this is also the default value).
399
400>*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`.
401
402Here is the call to `window.resolveLocalFileSystemURL`. The image URI is passed to this function from the success callback of `getPicture`. The success handler of `resolveLocalFileSystemURL` receives the FileEntry object.
403
404```js
405function getFileEntry(imgUri) {
406 window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
407
408 // Do something with the FileEntry object, like write to it, upload it, etc.
409 // writeFile(fileEntry, imgUri);
410 console.log("got file: " + fileEntry.fullPath);
411 // displayFileData(fileEntry.nativeURL, "Native URL");
412
413 }, function () {
414 // If don't get the FileEntry (which may happen when testing
415 // on some emulators), copy to a new FileEntry.
416 createNewFileEntry(imgUri);
417 });
418}
419```
420
421In the example shown in the preceding code, you call the app's `createNewFileEntry` function if you don't get a valid FileEntry object. The image URI returned from the Camera app should result in a valid FileEntry, but platform behavior on some emulators may be different for files returned from the file picker.
422
423>*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file).
424
425The code shown here creates a file in your app's cache (in sandboxed storage) named `tempFile.jpeg`. With the new FileEntry object, you can copy the image to the file or do something else like upload it.
426
427```js
428function createNewFileEntry(imgUri) {
429 window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
430
431 // JPEG file
432 dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) {
433
434 // Do something with it, like write to it, upload it, etc.
435 // writeFile(fileEntry, imgUri);
436 console.log("got file: " + fileEntry.fullPath);
437 // displayFileData(fileEntry.fullPath, "File copied to");
438
439 }, onErrorCreateFile);
440
441 }, onErrorResolveUrl);
442}
443```