openEventsPlatformApp/plugins/cordova-plugin-camera/README.md
plugins/cordova-plugin-camera/README.mdRaw
1---
2title: Camera
3description: Take pictures with the device camera.
4---
5<!---
6# license: Licensed to the Apache Software Foundation (ASF) under one
7# or more contributor license agreements. See the NOTICE file
8# distributed with this work for additional information
9# regarding copyright ownership. The ASF licenses this file
10# to you under the Apache License, Version 2.0 (the
11# "License"); you may not use this file except in compliance
12# with the License. You may obtain a copy of the License at
13#
14# http://www.apache.org/licenses/LICENSE-2.0
15#
16# Unless required by applicable law or agreed to in writing,
17# software distributed under the License is distributed on an
18# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
19# KIND, either express or implied. See the License for the
20# specific language governing permissions and limitations
21# under the License.
22-->
23
24|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
25|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
26|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-camera/)|[](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera/)|[](https://travis-ci.org/apache/cordova-plugin-camera)
27
28# cordova-plugin-camera
29
30This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from
31the system's image library.
32
33Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
34
35 document.addEventListener("deviceready", onDeviceReady, false);
36 function onDeviceReady() {
37 console.log(navigator.camera);
38 }
39
40
41## Installation
42
43This requires cordova 5.0+
44
45 cordova plugin add cordova-plugin-camera
46Older versions of cordova can still install via the __deprecated__ id
47
48 cordova plugin add org.apache.cordova.camera
49It is also possible to install via repo url directly ( unstable )
50
51 cordova plugin add https://github.com/apache/cordova-plugin-camera.git
52
53
54## How to Contribute
55
56Contributors are welcome! And we need your contributions to keep the project moving forward. You can [report bugs](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC), improve the documentation, or [contribute code](https://github.com/apache/cordova-plugin-camera/pulls).
57
58There is a specific [contributor workflow](http://wiki.apache.org/cordova/ContributorWorkflow) we recommend. Start reading there. More information is available on [our wiki](http://wiki.apache.org/cordova).
59
60:warning: **Found an issue?** File it on [JIRA issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20Reopened)%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Camera%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC).
61
62**Have a solution?** Send a [Pull Request](https://github.com/apache/cordova-plugin-camera/pulls).
63
64In order for your changes to be accepted, you need to sign and submit an Apache [ICLA](http://www.apache.org/licenses/#clas) (Individual Contributor License Agreement). Then your name will appear on the list of CLAs signed by [non-committers](https://people.apache.org/committer-index.html#unlistedclas) or [Cordova committers](http://people.apache.org/committers-by-project.html#cordova).
65
66**And don't forget to test and document your code.**
67
68
69## This documentation is generated by a tool
70
71:warning: Run `npm install` in the plugin repo to enable automatic docs generation if you plan to send a PR.
72[jsdoc-to-markdown](https://www.npmjs.com/package/jsdoc-to-markdown) is used to generate the docs.
73Documentation consists of template and API docs produced from the plugin JS code and should be regenerated before each commit (done automatically via [husky](https://github.com/typicode/husky), running `npm run gen-docs` script as a `precommit` hook - see `package.json` for details).
74
75
76
77### iOS Quirks
78
79Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist.
80
81- `NSCameraUsageDescription` describes the reason that the app accesses the user’s camera.
82- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library.
83
84When the system prompts the user to allow access, this string is displayed as part of the dialog box.
85
86To add this entry you can pass the following variables on plugin install.
87
88- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription`
89- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription`
90
91Example:
92
93 cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
94
95If you don't pass the variable, the plugin will add an empty string as value.
96
97---
98
99# API Reference <a name="reference"></a>
100
101
102* [camera](#module_camera)
103 * [.getPicture(successCallback, errorCallback, options)](#module_camera.getPicture)
104 * [.cleanup()](#module_camera.cleanup)
105 * [.onError](#module_camera.onError) : <code>function</code>
106 * [.onSuccess](#module_camera.onSuccess) : <code>function</code>
107 * [.CameraOptions](#module_camera.CameraOptions) : <code>Object</code>
108
109
110* [Camera](#module_Camera)
111 * [.DestinationType](#module_Camera.DestinationType) : <code>enum</code>
112 * [.EncodingType](#module_Camera.EncodingType) : <code>enum</code>
113 * [.MediaType](#module_Camera.MediaType) : <code>enum</code>
114 * [.PictureSourceType](#module_Camera.PictureSourceType) : <code>enum</code>
115 * [.PopoverArrowDirection](#module_Camera.PopoverArrowDirection) : <code>enum</code>
116 * [.Direction](#module_Camera.Direction) : <code>enum</code>
117
118* [CameraPopoverHandle](#module_CameraPopoverHandle)
119* [CameraPopoverOptions](#module_CameraPopoverOptions)
120
121---
122
123<a name="module_camera"></a>
124
125## camera
126<a name="module_camera.getPicture"></a>
127
128### camera.getPicture(successCallback, errorCallback, options)
129Takes a photo using the camera, or retrieves a photo from the device's
130image gallery. The image is passed to the success callback as a
131Base64-encoded `String`, or as the URI for the image file.
132
133The `camera.getPicture` function opens the device's default camera
134application that allows users to snap pictures by default - this behavior occurs,
135when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`](#module_Camera.PictureSourceType).
136Once the user snaps the photo, the camera application closes and the application is restored.
137
138If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or
139`Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays
140that allows users to select an existing image.
141
142The return value is sent to the [`cameraSuccess`](#module_camera.onSuccess) callback function, in
143one of the following formats, depending on the specified
144`cameraOptions`:
145
146- A `String` containing the Base64-encoded photo image.
147- A `String` representing the image file location on local storage (default).
148
149You can do whatever you want with the encoded image or URI, for
150example:
151
152- Render the image in an `<img>` tag, as in the example below
153- Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
154- Post the data to a remote server
155
156__NOTE__: Photo resolution on newer devices is quite good. Photos
157selected from the device's gallery are not downscaled to a lower
158quality, even if a `quality` parameter is specified. To avoid common
159memory problems, set `Camera.destinationType` to `FILE_URI` rather
160than `DATA_URL`.
161
162__Supported Platforms__
163
164- Android
165- BlackBerry
166- Browser
167- Firefox
168- FireOS
169- iOS
170- Windows
171- WP8
172- Ubuntu
173
174More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).
175
176**Kind**: static method of <code>[camera](#module_camera)</code>
177
178| Param | Type | Description |
179| --- | --- | --- |
180| successCallback | <code>[onSuccess](#module_camera.onSuccess)</code> | |
181| errorCallback | <code>[onError](#module_camera.onError)</code> | |
182| options | <code>[CameraOptions](#module_camera.CameraOptions)</code> | CameraOptions |
183
184**Example**
185```js
186navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
187```
188<a name="module_camera.cleanup"></a>
189
190### camera.cleanup()
191Removes intermediate image files that are kept in temporary storage
192after calling [`camera.getPicture`](#module_camera.getPicture). Applies only when the value of
193`Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the
194`Camera.destinationType` equals `Camera.DestinationType.FILE_URI`.
195
196__Supported Platforms__
197
198- iOS
199
200**Kind**: static method of <code>[camera](#module_camera)</code>
201**Example**
202```js
203navigator.camera.cleanup(onSuccess, onFail);
204
205function onSuccess() {
206 console.log("Camera cleanup success.")
207}
208
209function onFail(message) {
210 alert('Failed because: ' + message);
211}
212```
213<a name="module_camera.onError"></a>
214
215### camera.onError : <code>function</code>
216Callback function that provides an error message.
217
218**Kind**: static typedef of <code>[camera](#module_camera)</code>
219
220| Param | Type | Description |
221| --- | --- | --- |
222| message | <code>string</code> | The message is provided by the device's native code. |
223
224<a name="module_camera.onSuccess"></a>
225
226### camera.onSuccess : <code>function</code>
227Callback function that provides the image data.
228
229**Kind**: static typedef of <code>[camera](#module_camera)</code>
230
231| Param | Type | Description |
232| --- | --- | --- |
233| imageData | <code>string</code> | Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`](#module_camera.CameraOptions) in effect. |
234
235**Example**
236```js
237// Show image
238//
239function cameraCallback(imageData) {
240 var image = document.getElementById('myImage');
241 image.src = "data:image/jpeg;base64," + imageData;
242}
243```
244<a name="module_camera.CameraOptions"></a>
245
246### camera.CameraOptions : <code>Object</code>
247Optional parameters to customize the camera settings.
248* [Quirks](#CameraOptions-quirks)
249
250**Kind**: static typedef of <code>[camera](#module_camera)</code>
251**Properties**
252
253| Name | Type | Default | Description |
254| --- | --- | --- | --- |
255| quality | <code>number</code> | <code>50</code> | Quality 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.) |
256| destinationType | <code>[DestinationType](#module_Camera.DestinationType)</code> | <code>FILE_URI</code> | Choose the format of the return value. |
257| sourceType | <code>[PictureSourceType](#module_Camera.PictureSourceType)</code> | <code>CAMERA</code> | Set the source of the picture. |
258| allowEdit | <code>Boolean</code> | <code>true</code> | Allow simple editing of image before selection. |
259| encodingType | <code>[EncodingType](#module_Camera.EncodingType)</code> | <code>JPEG</code> | Choose the returned image file's encoding. |
260| targetWidth | <code>number</code> | | Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant. |
261| targetHeight | <code>number</code> | | Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant. |
262| mediaType | <code>[MediaType](#module_Camera.MediaType)</code> | <code>PICTURE</code> | Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`. |
263| correctOrientation | <code>Boolean</code> | | Rotate the image to correct for the orientation of the device during capture. |
264| saveToPhotoAlbum | <code>Boolean</code> | | Save the image to the photo album on the device after capture. |
265| popoverOptions | <code>[CameraPopoverOptions](#module_CameraPopoverOptions)</code> | | iOS-only options that specify popover location in iPad. |
266| cameraDirection | <code>[Direction](#module_Camera.Direction)</code> | <code>BACK</code> | Choose the camera to use (front- or back-facing). |
267
268---
269
270<a name="module_Camera"></a>
271
272## Camera
273<a name="module_Camera.DestinationType"></a>
274
275### Camera.DestinationType : <code>enum</code>
276Defines the output format of `Camera.getPicture` call.
277_Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
278`PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
279disable any image modifications (resize, quality change, cropping, etc.) due
280to implementation specific.
281
282**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
283**Properties**
284
285| Name | Type | Default | Description |
286| --- | --- | --- | --- |
287| DATA_URL | <code>number</code> | <code>0</code> | Return base64 encoded string. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI or NATIVE_URI if possible |
288| FILE_URI | <code>number</code> | <code>1</code> | Return file uri (content://media/external/images/media/2 for Android) |
289| NATIVE_URI | <code>number</code> | <code>2</code> | Return native uri (eg. asset-library://... for iOS) |
290
291<a name="module_Camera.EncodingType"></a>
292
293### Camera.EncodingType : <code>enum</code>
294**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
295**Properties**
296
297| Name | Type | Default | Description |
298| --- | --- | --- | --- |
299| JPEG | <code>number</code> | <code>0</code> | Return JPEG encoded image |
300| PNG | <code>number</code> | <code>1</code> | Return PNG encoded image |
301
302<a name="module_Camera.MediaType"></a>
303
304### Camera.MediaType : <code>enum</code>
305**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
306**Properties**
307
308| Name | Type | Default | Description |
309| --- | --- | --- | --- |
310| PICTURE | <code>number</code> | <code>0</code> | Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType |
311| VIDEO | <code>number</code> | <code>1</code> | Allow selection of video only, ONLY RETURNS URL |
312| ALLMEDIA | <code>number</code> | <code>2</code> | Allow selection from all media types |
313
314<a name="module_Camera.PictureSourceType"></a>
315
316### Camera.PictureSourceType : <code>enum</code>
317Defines the output format of `Camera.getPicture` call.
318_Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
319along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
320change, cropping, etc.) due to implementation specific.
321
322**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
323**Properties**
324
325| Name | Type | Default | Description |
326| --- | --- | --- | --- |
327| PHOTOLIBRARY | <code>number</code> | <code>0</code> | Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) |
328| CAMERA | <code>number</code> | <code>1</code> | Take picture from camera |
329| SAVEDPHOTOALBUM | <code>number</code> | <code>2</code> | Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) |
330
331<a name="module_Camera.PopoverArrowDirection"></a>
332
333### Camera.PopoverArrowDirection : <code>enum</code>
334Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
335
336**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
337**Properties**
338
339| Name | Type | Default |
340| --- | --- | --- |
341| ARROW_UP | <code>number</code> | <code>1</code> |
342| ARROW_DOWN | <code>number</code> | <code>2</code> |
343| ARROW_LEFT | <code>number</code> | <code>4</code> |
344| ARROW_RIGHT | <code>number</code> | <code>8</code> |
345| ARROW_ANY | <code>number</code> | <code>15</code> |
346
347<a name="module_Camera.Direction"></a>
348
349### Camera.Direction : <code>enum</code>
350**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
351**Properties**
352
353| Name | Type | Default | Description |
354| --- | --- | --- | --- |
355| BACK | <code>number</code> | <code>0</code> | Use the back-facing camera |
356| FRONT | <code>number</code> | <code>1</code> | Use the front-facing camera |
357
358---
359
360<a name="module_CameraPopoverOptions"></a>
361
362## CameraPopoverOptions
363iOS-only parameters that specify the anchor element location and arrow
364direction of the popover when selecting images from an iPad's library
365or album.
366Note that the size of the popover may change to adjust to the
367direction of the arrow and orientation of the screen. Make sure to
368account for orientation changes when specifying the anchor element
369location.
370
371
372| Param | Type | Default | Description |
373| --- | --- | --- | --- |
374| [x] | <code>Number</code> | <code>0</code> | x pixel coordinate of screen element onto which to anchor the popover. |
375| [y] | <code>Number</code> | <code>32</code> | y pixel coordinate of screen element onto which to anchor the popover. |
376| [width] | <code>Number</code> | <code>320</code> | width, in pixels, of the screen element onto which to anchor the popover. |
377| [height] | <code>Number</code> | <code>480</code> | height, in pixels, of the screen element onto which to anchor the popover. |
378| [arrowDir] | <code>[PopoverArrowDirection](#module_Camera.PopoverArrowDirection)</code> | <code>ARROW_ANY</code> | Direction the arrow on the popover should point. |
379
380---
381
382<a name="module_CameraPopoverHandle"></a>
383
384## CameraPopoverHandle
385A handle to an image picker popover.
386
387__Supported Platforms__
388
389- iOS
390
391**Example**
392```js
393navigator.camera.getPicture(onSuccess, onFail,
394{
395 destinationType: Camera.DestinationType.FILE_URI,
396 sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
397 popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
398});
399
400// Reposition the popover if the orientation changes.
401window.onorientationchange = function() {
402 var cameraPopoverHandle = new CameraPopoverHandle();
403 var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
404 cameraPopoverHandle.setPosition(cameraPopoverOptions);
405}
406```
407---
408
409
410## `camera.getPicture` Errata
411
412#### Example <a name="camera-getPicture-examples"></a>
413
414Take a photo and retrieve the image's file location:
415
416 navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
417 destinationType: Camera.DestinationType.FILE_URI });
418
419 function onSuccess(imageURI) {
420 var image = document.getElementById('myImage');
421 image.src = imageURI;
422 }
423
424 function onFail(message) {
425 alert('Failed because: ' + message);
426 }
427
428Take a photo and retrieve it as a Base64-encoded image:
429
430 /**
431 * Warning: Using DATA_URL is not recommended! The DATA_URL destination
432 * type is very memory intensive, even with a low quality setting. Using it
433 * can result in out of memory errors and application crashes. Use FILE_URI
434 * or NATIVE_URI instead.
435 */
436 navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
437 destinationType: Camera.DestinationType.DATA_URL
438 });
439
440 function onSuccess(imageData) {
441 var image = document.getElementById('myImage');
442 image.src = "data:image/jpeg;base64," + imageData;
443 }
444
445 function onFail(message) {
446 alert('Failed because: ' + message);
447 }
448
449#### Preferences (iOS)
450
451- __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.
452
453 <preference name="CameraUsesGeolocation" value="false" />
454
455#### Amazon Fire OS Quirks <a name="camera-getPicture-quirks"></a>
456
457Amazon Fire OS uses intents to launch the camera activity on the device to capture
458images, and on phones with low memory, the Cordova activity may be killed. In this
459scenario, the image may not appear when the Cordova activity is restored.
460
461#### Android Quirks
462
463Android uses intents to launch the camera activity on the device to capture
464images, and on phones with low memory, the Cordova activity may be killed. In this
465scenario, the result from the plugin call will be delivered via the resume event.
466See [the Android Lifecycle guide][android_lifecycle]
467for more information. The `pendingResult.result` value will contain the value that
468would be passed to the callbacks (either the URI/URL or an error message). Check
469the `pendingResult.pluginStatus` to determine whether or not the call was
470successful.
471
472#### Browser Quirks
473
474Can only return photos as Base64-encoded image.
475
476#### Firefox OS Quirks
477
478Camera plugin is currently implemented using [Web Activities][web_activities].
479
480#### iOS Quirks
481
482Including a JavaScript `alert()` in either of the callback functions
483can cause problems. Wrap the alert within a `setTimeout()` to allow
484the iOS image picker or popover to fully close before the alert
485displays:
486
487 setTimeout(function() {
488 // do your thing here!
489 }, 0);
490
491#### Windows Phone 7 Quirks
492
493Invoking the native camera application while the device is connected
494via Zune does not work, and triggers an error callback.
495
496#### Windows quirks
497
498On Windows Phone 8.1 using `SAVEDPHOTOALBUM` or `PHOTOLIBRARY` as a source type causes application to suspend until file picker returns the selected image and
499then 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
500start page from scratch and success and error callbacks will never be called.
501
502To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page.
503
504More 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)
505
506#### Tizen Quirks
507
508Tizen only supports a `destinationType` of
509`Camera.DestinationType.FILE_URI` and a `sourceType` of
510`Camera.PictureSourceType.PHOTOLIBRARY`.
511
512
513## `CameraOptions` Errata <a name="CameraOptions-quirks"></a>
514
515#### Amazon Fire OS Quirks
516
517- Any `cameraDirection` value results in a back-facing photo.
518
519- Ignores the `allowEdit` parameter.
520
521- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
522
523#### Android Quirks
524
525- Any `cameraDirection` value results in a back-facing photo.
526
527- **`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.
528
529- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
530
531- 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.
532
533#### BlackBerry 10 Quirks
534
535- Ignores the `quality` parameter.
536
537- Ignores the `allowEdit` parameter.
538
539- `Camera.MediaType` is not supported.
540
541- Ignores the `correctOrientation` parameter.
542
543- Ignores the `cameraDirection` parameter.
544
545#### Firefox OS Quirks
546
547- Ignores the `quality` parameter.
548
549- `Camera.DestinationType` is ignored and equals `1` (image file URI)
550
551- Ignores the `allowEdit` parameter.
552
553- Ignores the `PictureSourceType` parameter (user chooses it in a dialog window)
554
555- Ignores the `encodingType`
556
557- Ignores the `targetWidth` and `targetHeight`
558
559- `Camera.MediaType` is not supported.
560
561- Ignores the `correctOrientation` parameter.
562
563- Ignores the `cameraDirection` parameter.
564
565#### iOS Quirks
566
567- 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.
568
569- When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter.
570
571- When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture.
572
573#### Tizen Quirks
574
575- options not supported
576
577- always returns a FILE URI
578
579#### Windows Phone 7 and 8 Quirks
580
581- Ignores the `allowEdit` parameter.
582
583- Ignores the `correctOrientation` parameter.
584
585- Ignores the `cameraDirection` parameter.
586
587- 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].
588
589- Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.
590
591[android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html
592[web_activities]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
593[wp8_bug]: https://issues.apache.org/jira/browse/CB-2083
594[msdn_wp8_docs]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx
595
596## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails <a name="sample"></a>
597
598The 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:
599
600* Open the Camera app and [take a Picture](#takePicture)
601* Take a picture and [return thumbnails](#getThumbnails) (resized picture)
602* Take a picture and [generate a FileEntry object](#convert)
603* [Select a file](#selectFile) from the picture library
604* Select a JPEG image and [return thumbnails](#getFileThumbnails) (resized image)
605* Select an image and [generate a FileEntry object](#convert)
606
607## Take a Picture <a name="takePicture"></a>
608
609Before 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.
610
611```js
612function setOptions(srcType) {
613 var options = {
614 // Some common settings are 20, 50, and 100
615 quality: 50,
616 destinationType: Camera.DestinationType.FILE_URI,
617 // In this app, dynamically set the picture source, Camera or photo gallery
618 sourceType: srcType,
619 encodingType: Camera.EncodingType.JPEG,
620 mediaType: Camera.MediaType.PICTURE,
621 allowEdit: true,
622 correctOrientation: true //Corrects Android orientation quirks
623 }
624 return options;
625}
626```
627
628Typically, 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.
629
630You 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.
631
632```js
633function openCamera(selection) {
634
635 var srcType = Camera.PictureSourceType.CAMERA;
636 var options = setOptions(srcType);
637 var func = createNewFileEntry;
638
639 navigator.camera.getPicture(function cameraSuccess(imageUri) {
640
641 displayImage(imageUri);
642 // You may choose to copy the picture, save it somewhere, or upload.
643 func(imageUri);
644
645 }, function cameraError(error) {
646 console.debug("Unable to obtain picture: " + error, "app");
647
648 }, options);
649}
650```
651
652Once 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.
653
654```js
655function displayImage(imgUri) {
656
657 var elem = document.getElementById('imageFile');
658 elem.src = imgUri;
659}
660```
661
662To 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.
663
664```html
665<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 *">
666```
667
668## Take a Picture and Return Thumbnails (Resize the Picture) <a name="getThumbnails"></a>
669
670To 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).
671
672```js
673function openCamera(selection) {
674
675 var srcType = Camera.PictureSourceType.CAMERA;
676 var options = setOptions(srcType);
677 var func = createNewFileEntry;
678
679 if (selection == "camera-thmb") {
680 options.targetHeight = 100;
681 options.targetWidth = 100;
682 }
683
684 navigator.camera.getPicture(function cameraSuccess(imageUri) {
685
686 // Do something
687
688 }, function cameraError(error) {
689 console.debug("Unable to obtain picture: " + error, "app");
690
691 }, options);
692}
693```
694
695## Select a File from the Picture Library <a name="selectFile"></a>
696
697When 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.
698
699```js
700function openFilePicker(selection) {
701
702 var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
703 var options = setOptions(srcType);
704 var func = createNewFileEntry;
705
706 navigator.camera.getPicture(function cameraSuccess(imageUri) {
707
708 // Do something
709
710 }, function cameraError(error) {
711 console.debug("Unable to obtain picture: " + error, "app");
712
713 }, options);
714}
715```
716
717## Select an Image and Return Thumbnails (resized images) <a name="getFileThumbnails"></a>
718
719Resizing a file selected with the file picker works just like resizing using the Camera app; set the `targetHeight` and `targetWidth` options.
720
721```js
722function openFilePicker(selection) {
723
724 var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
725 var options = setOptions(srcType);
726 var func = createNewFileEntry;
727
728 if (selection == "picker-thmb") {
729 // To downscale a selected image,
730 // Camera.EncodingType (e.g., JPEG) must match the selected image type.
731 options.targetHeight = 100;
732 options.targetWidth = 100;
733 }
734
735 navigator.camera.getPicture(function cameraSuccess(imageUri) {
736
737 // Do something with image
738
739 }, function cameraError(error) {
740 console.debug("Unable to obtain picture: " + error, "app");
741
742 }, options);
743}
744```
745
746## Take a picture and get a FileEntry Object <a name="convert"></a>
747
748If 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).
749
750>*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`.
751
752Here 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.
753
754```js
755function getFileEntry(imgUri) {
756 window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
757
758 // Do something with the FileEntry object, like write to it, upload it, etc.
759 // writeFile(fileEntry, imgUri);
760 console.log("got file: " + fileEntry.fullPath);
761 // displayFileData(fileEntry.nativeURL, "Native URL");
762
763 }, function () {
764 // If don't get the FileEntry (which may happen when testing
765 // on some emulators), copy to a new FileEntry.
766 createNewFileEntry(imgUri);
767 });
768}
769```
770
771In 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.
772
773>*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file).
774
775The 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.
776
777```js
778function createNewFileEntry(imgUri) {
779 window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
780
781 // JPEG file
782 dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) {
783
784 // Do something with it, like write to it, upload it, etc.
785 // writeFile(fileEntry, imgUri);
786 console.log("got file: " + fileEntry.fullPath);
787 // displayFileData(fileEntry.fullPath, "File copied to");
788
789 }, onErrorCreateFile);
790
791 }, onErrorResolveUrl);
792}
793```