UNPKG

32.2 kBMarkdownView Raw
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|AppVeyor|Travis CI|
25|:-:|:-:|
26|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-camera?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-camera)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg?branch=master)](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, 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**Have a solution?** Send a [Pull Request](https://github.com/apache/cordova-plugin-camera/pulls).
61
62In 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).
63
64**And don't forget to test and document your code.**
65
66### iOS Quirks
67
68Since iOS 10 it's mandatory to provide an usage description in the `info.plist` if trying to access privacy-sensitive data. When the system prompts the user to allow access, this usage description string will displayed as part of the permission dialog box, but if you didn't provide the usage description, the app will crash before showing the dialog. Also, Apple will reject apps that access private data but don't provide an usage description.
69
70This plugins requires the following usage descriptions:
71
72- `NSCameraUsageDescription` specifies the reason for your app to access the device's camera.
73- `NSPhotoLibraryUsageDescription` specifies the reason for your app to access the user's photo library.
74- `NSLocationWhenInUseUsageDescription` specifies the reason for your app to access the user's location information while your app is in use. (Set it if you have `CameraUsesGeolocation` preference set to `true`)
75- `NSPhotoLibraryAddUsageDescription` specifies the reason for your app to get write-only access to the user's photo library
76
77To add these entries into the `info.plist`, you can use the `edit-config` tag in the `config.xml` like this:
78
79```
80<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
81 <string>need camera access to take pictures</string>
82</edit-config>
83```
84
85```
86<edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge">
87 <string>need photo library access to get pictures from there</string>
88</edit-config>
89```
90
91```
92<edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
93 <string>need location access to find things nearby</string>
94</edit-config>
95```
96
97```
98<edit-config target="NSPhotoLibraryAddUsageDescription" file="*-Info.plist" mode="merge">
99 <string>need photo library access to save pictures there</string>
100</edit-config>
101```
102
103---
104
105# API Reference <a name="reference"></a>
106
107
108* [camera](#module_camera)
109 * [.getPicture(successCallback, errorCallback, options)](#module_camera.getPicture)
110 * [.cleanup()](#module_camera.cleanup)
111 * [.onError](#module_camera.onError) : <code>function</code>
112 * [.onSuccess](#module_camera.onSuccess) : <code>function</code>
113 * [.CameraOptions](#module_camera.CameraOptions) : <code>Object</code>
114
115
116* [Camera](#module_Camera)
117 * [.DestinationType](#module_Camera.DestinationType) : <code>enum</code>
118 * [.EncodingType](#module_Camera.EncodingType) : <code>enum</code>
119 * [.MediaType](#module_Camera.MediaType) : <code>enum</code>
120 * [.PictureSourceType](#module_Camera.PictureSourceType) : <code>enum</code>
121 * [.PopoverArrowDirection](#module_Camera.PopoverArrowDirection) : <code>enum</code>
122 * [.Direction](#module_Camera.Direction) : <code>enum</code>
123
124* [CameraPopoverHandle](#module_CameraPopoverHandle)
125* [CameraPopoverOptions](#module_CameraPopoverOptions)
126
127---
128
129<a name="module_camera"></a>
130
131## camera
132<a name="module_camera.getPicture"></a>
133
134### camera.getPicture(successCallback, errorCallback, options)
135Takes a photo using the camera, or retrieves a photo from the device's
136image gallery. The image is passed to the success callback as a
137Base64-encoded `String`, or as the URI for the image file.
138
139The `camera.getPicture` function opens the device's default camera
140application that allows users to snap pictures by default - this behavior occurs,
141when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`](#module_Camera.PictureSourceType).
142Once the user snaps the photo, the camera application closes and the application is restored.
143
144If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or
145`Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays
146that allows users to select an existing image.
147
148The return value is sent to the [`cameraSuccess`](#module_camera.onSuccess) callback function, in
149one of the following formats, depending on the specified
150`cameraOptions`:
151
152- A `String` containing the Base64-encoded photo image.
153- A `String` representing the image file location on local storage (default).
154
155You can do whatever you want with the encoded image or URI, for
156example:
157
158- Render the image in an `<img>` tag, as in the example below
159- Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
160- Post the data to a remote server
161
162__NOTE__: Photo resolution on newer devices is quite good. Photos
163selected from the device's gallery are not downscaled to a lower
164quality, even if a `quality` parameter is specified. To avoid common
165memory problems, set `Camera.destinationType` to `FILE_URI` rather
166than `DATA_URL`.
167
168__Supported Platforms__
169
170- Android
171- Browser
172- iOS
173- Windows
174- OSX
175
176More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).
177
178**Kind**: static method of <code>[camera](#module_camera)</code>
179
180| Param | Type | Description |
181| --- | --- | --- |
182| successCallback | <code>[onSuccess](#module_camera.onSuccess)</code> | |
183| errorCallback | <code>[onError](#module_camera.onError)</code> | |
184| options | <code>[CameraOptions](#module_camera.CameraOptions)</code> | CameraOptions |
185
186**Example**
187```js
188navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
189```
190<a name="module_camera.cleanup"></a>
191
192### camera.cleanup()
193Removes intermediate image files that are kept in temporary storage
194after calling [`camera.getPicture`](#module_camera.getPicture). Applies only when the value of
195`Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the
196`Camera.destinationType` equals `Camera.DestinationType.FILE_URI`.
197
198__Supported Platforms__
199
200- iOS
201
202**Kind**: static method of <code>[camera](#module_camera)</code>
203**Example**
204```js
205navigator.camera.cleanup(onSuccess, onFail);
206
207function onSuccess() {
208 console.log("Camera cleanup success.")
209}
210
211function onFail(message) {
212 alert('Failed because: ' + message);
213}
214```
215<a name="module_camera.onError"></a>
216
217### camera.onError : <code>function</code>
218Callback function that provides an error message.
219
220**Kind**: static typedef of <code>[camera](#module_camera)</code>
221
222| Param | Type | Description |
223| --- | --- | --- |
224| message | <code>string</code> | The message is provided by the device's native code. |
225
226<a name="module_camera.onSuccess"></a>
227
228### camera.onSuccess : <code>function</code>
229Callback function that provides the image data.
230
231**Kind**: static typedef of <code>[camera](#module_camera)</code>
232
233| Param | Type | Description |
234| --- | --- | --- |
235| imageData | <code>string</code> | Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`](#module_camera.CameraOptions) in effect. |
236
237**Example**
238```js
239// Show image
240//
241function cameraCallback(imageData) {
242 var image = document.getElementById('myImage');
243 image.src = "data:image/jpeg;base64," + imageData;
244}
245```
246<a name="module_camera.CameraOptions"></a>
247
248### camera.CameraOptions : <code>Object</code>
249Optional parameters to customize the camera settings.
250* [Quirks](#CameraOptions-quirks)
251
252**Kind**: static typedef of <code>[camera](#module_camera)</code>
253**Properties**
254
255| Name | Type | Default | Description |
256| --- | --- | --- | --- |
257| 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.) |
258| destinationType | <code>[DestinationType](#module_Camera.DestinationType)</code> | <code>FILE_URI</code> | Choose the format of the return value. |
259| sourceType | <code>[PictureSourceType](#module_Camera.PictureSourceType)</code> | <code>CAMERA</code> | Set the source of the picture. |
260| allowEdit | <code>Boolean</code> | <code>false</code> | Allow simple editing of image before selection. |
261| encodingType | <code>[EncodingType](#module_Camera.EncodingType)</code> | <code>JPEG</code> | Choose the returned image file's encoding. |
262| targetWidth | <code>number</code> | | Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant. |
263| targetHeight | <code>number</code> | | Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant. |
264| 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`. |
265| correctOrientation | <code>Boolean</code> | | Rotate the image to correct for the orientation of the device during capture. |
266| saveToPhotoAlbum | <code>Boolean</code> | | Save the image to the photo album on the device after capture. |
267| popoverOptions | <code>[CameraPopoverOptions](#module_CameraPopoverOptions)</code> | | iOS-only options that specify popover location in iPad. |
268| cameraDirection | <code>[Direction](#module_Camera.Direction)</code> | <code>BACK</code> | Choose the camera to use (front- or back-facing). |
269
270---
271
272<a name="module_Camera"></a>
273
274## Camera
275<a name="module_Camera.DestinationType"></a>
276
277### Camera.DestinationType : <code>enum</code>
278Defines the output format of `Camera.getPicture` call.
279_Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
280`PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
281disable any image modifications (resize, quality change, cropping, etc.) due
282to implementation specific.
283
284**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
285**Properties**
286
287| Name | Type | Default | Description |
288| --- | --- | --- | --- |
289| 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 |
290| FILE_URI | <code>number</code> | <code>1</code> | Return file uri (content://media/external/images/media/2 for Android) |
291| NATIVE_URI | <code>number</code> | <code>2</code> | Return native uri (eg. asset-library://... for iOS) |
292
293<a name="module_Camera.EncodingType"></a>
294
295### Camera.EncodingType : <code>enum</code>
296**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
297**Properties**
298
299| Name | Type | Default | Description |
300| --- | --- | --- | --- |
301| JPEG | <code>number</code> | <code>0</code> | Return JPEG encoded image |
302| PNG | <code>number</code> | <code>1</code> | Return PNG encoded image |
303
304<a name="module_Camera.MediaType"></a>
305
306### Camera.MediaType : <code>enum</code>
307**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
308**Properties**
309
310| Name | Type | Default | Description |
311| --- | --- | --- | --- |
312| PICTURE | <code>number</code> | <code>0</code> | Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType |
313| VIDEO | <code>number</code> | <code>1</code> | Allow selection of video only, ONLY RETURNS URL |
314| ALLMEDIA | <code>number</code> | <code>2</code> | Allow selection from all media types |
315
316<a name="module_Camera.PictureSourceType"></a>
317
318### Camera.PictureSourceType : <code>enum</code>
319Defines the output format of `Camera.getPicture` call.
320_Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
321along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
322change, cropping, etc.) due to implementation specific.
323
324**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
325**Properties**
326
327| Name | Type | Default | Description |
328| --- | --- | --- | --- |
329| PHOTOLIBRARY | <code>number</code> | <code>0</code> | Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) |
330| CAMERA | <code>number</code> | <code>1</code> | Take picture from camera |
331| SAVEDPHOTOALBUM | <code>number</code> | <code>2</code> | Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) |
332
333<a name="module_Camera.PopoverArrowDirection"></a>
334
335### Camera.PopoverArrowDirection : <code>enum</code>
336Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
337
338**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
339**Properties**
340
341| Name | Type | Default |
342| --- | --- | --- |
343| ARROW_UP | <code>number</code> | <code>1</code> |
344| ARROW_DOWN | <code>number</code> | <code>2</code> |
345| ARROW_LEFT | <code>number</code> | <code>4</code> |
346| ARROW_RIGHT | <code>number</code> | <code>8</code> |
347| ARROW_ANY | <code>number</code> | <code>15</code> |
348
349<a name="module_Camera.Direction"></a>
350
351### Camera.Direction : <code>enum</code>
352**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
353**Properties**
354
355| Name | Type | Default | Description |
356| --- | --- | --- | --- |
357| BACK | <code>number</code> | <code>0</code> | Use the back-facing camera |
358| FRONT | <code>number</code> | <code>1</code> | Use the front-facing camera |
359
360---
361
362<a name="module_CameraPopoverOptions"></a>
363
364## CameraPopoverOptions
365iOS-only parameters that specify the anchor element location and arrow
366direction of the popover when selecting images from an iPad's library
367or album.
368Note that the size of the popover may change to adjust to the
369direction of the arrow and orientation of the screen. Make sure to
370account for orientation changes when specifying the anchor element
371location.
372
373
374| Param | Type | Default | Description |
375| --- | --- | --- | --- |
376| [x] | <code>Number</code> | <code>0</code> | x pixel coordinate of screen element onto which to anchor the popover. |
377| [y] | <code>Number</code> | <code>32</code> | y pixel coordinate of screen element onto which to anchor the popover. |
378| [width] | <code>Number</code> | <code>320</code> | width, in pixels, of the screen element onto which to anchor the popover. |
379| [height] | <code>Number</code> | <code>480</code> | height, in pixels, of the screen element onto which to anchor the popover. |
380| [arrowDir] | <code>[PopoverArrowDirection](#module_Camera.PopoverArrowDirection)</code> | <code>ARROW_ANY</code> | Direction the arrow on the popover should point. |
381| [popoverWidth] | <code>Number</code> | <code>0</code> | width of the popover (0 or not specified will use apple's default width). |
382| [popoverHeight] | <code>Number</code> | <code>0</code> | height of the popover (0 or not specified will use apple's default height). |
383
384---
385
386<a name="module_CameraPopoverHandle"></a>
387
388## CameraPopoverHandle
389A handle to an image picker popover.
390
391__Supported Platforms__
392
393- iOS
394
395**Example**
396```js
397navigator.camera.getPicture(onSuccess, onFail,
398{
399 destinationType: Camera.DestinationType.FILE_URI,
400 sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
401 popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY, 300, 600)
402});
403
404// Reposition the popover if the orientation changes.
405window.onorientationchange = function() {
406 var cameraPopoverHandle = new CameraPopoverHandle();
407 var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY, 400, 500);
408 cameraPopoverHandle.setPosition(cameraPopoverOptions);
409}
410```
411---
412
413
414## `camera.getPicture` Errata
415
416#### Example <a name="camera-getPicture-examples"></a>
417
418Take a photo and retrieve the image's file location:
419
420 navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
421 destinationType: Camera.DestinationType.FILE_URI });
422
423 function onSuccess(imageURI) {
424 var image = document.getElementById('myImage');
425 image.src = imageURI;
426 }
427
428 function onFail(message) {
429 alert('Failed because: ' + message);
430 }
431
432Take a photo and retrieve it as a Base64-encoded image:
433
434 /**
435 * Warning: Using DATA_URL is not recommended! The DATA_URL destination
436 * type is very memory intensive, even with a low quality setting. Using it
437 * can result in out of memory errors and application crashes. Use FILE_URI
438 * or NATIVE_URI instead.
439 */
440 navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
441 destinationType: Camera.DestinationType.DATA_URL
442 });
443
444 function onSuccess(imageData) {
445 var image = document.getElementById('myImage');
446 image.src = "data:image/jpeg;base64," + imageData;
447 }
448
449 function onFail(message) {
450 alert('Failed because: ' + message);
451 }
452
453#### Preferences (iOS)
454
455- __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.
456
457 <preference name="CameraUsesGeolocation" value="false" />
458
459#### Android Quirks
460
461Android uses intents to launch the camera activity on the device to capture
462images, and on phones with low memory, the Cordova activity may be killed. In this
463scenario, the result from the plugin call will be delivered via the resume event.
464See [the Android Lifecycle guide][android_lifecycle]
465for more information. The `pendingResult.result` value will contain the value that
466would be passed to the callbacks (either the URI/URL or an error message). Check
467the `pendingResult.pluginStatus` to determine whether or not the call was
468successful.
469
470#### Browser Quirks
471
472Can only return photos as Base64-encoded image.
473
474#### iOS Quirks
475
476Including a JavaScript `alert()` in either of the callback functions
477can cause problems. Wrap the alert within a `setTimeout()` to allow
478the iOS image picker or popover to fully close before the alert
479displays:
480
481 setTimeout(function() {
482 // do your thing here!
483 }, 0);
484
485#### Windows Phone 7 Quirks
486
487Invoking the native camera application while the device is connected
488via Zune does not work, and triggers an error callback.
489
490#### Windows quirks
491
492On Windows Phone 8.1 using `SAVEDPHOTOALBUM` or `PHOTOLIBRARY` as a source type causes application to suspend until file picker returns the selected image and
493then 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
494start page from scratch and success and error callbacks will never be called.
495
496To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page.
497
498More 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)
499
500## `CameraOptions` Errata <a name="CameraOptions-quirks"></a>
501
502#### Android Quirks
503
504- Any `cameraDirection` value results in a back-facing photo. (= You can only use the back camera)
505
506- **`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.
507
508- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
509
510- 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.
511
512#### iOS Quirks
513
514- 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.
515
516- When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter.
517
518- When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture.
519
520[android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html
521
522## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails <a name="sample"></a>
523
524The 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:
525
526* Open the Camera app and [take a Picture](#takePicture)
527* Take a picture and [return thumbnails](#getThumbnails) (resized picture)
528* Take a picture and [generate a FileEntry object](#convert)
529* [Select a file](#selectFile) from the picture library
530* Select a JPEG image and [return thumbnails](#getFileThumbnails) (resized image)
531* Select an image and [generate a FileEntry object](#convert)
532
533## Take a Picture <a name="takePicture"></a>
534
535Before 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.
536
537```js
538function setOptions(srcType) {
539 var options = {
540 // Some common settings are 20, 50, and 100
541 quality: 50,
542 destinationType: Camera.DestinationType.FILE_URI,
543 // In this app, dynamically set the picture source, Camera or photo gallery
544 sourceType: srcType,
545 encodingType: Camera.EncodingType.JPEG,
546 mediaType: Camera.MediaType.PICTURE,
547 allowEdit: true,
548 correctOrientation: true //Corrects Android orientation quirks
549 }
550 return options;
551}
552```
553
554Typically, 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.
555
556You 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.
557
558```js
559function openCamera(selection) {
560
561 var srcType = Camera.PictureSourceType.CAMERA;
562 var options = setOptions(srcType);
563 var func = createNewFileEntry;
564
565 navigator.camera.getPicture(function cameraSuccess(imageUri) {
566
567 displayImage(imageUri);
568 // You may choose to copy the picture, save it somewhere, or upload.
569 func(imageUri);
570
571 }, function cameraError(error) {
572 console.debug("Unable to obtain picture: " + error, "app");
573
574 }, options);
575}
576```
577
578Once 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.
579
580```js
581function displayImage(imgUri) {
582
583 var elem = document.getElementById('imageFile');
584 elem.src = imgUri;
585}
586```
587
588To 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.
589
590```html
591<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 *">
592```
593
594## Take a Picture and Return Thumbnails (Resize the Picture) <a name="getThumbnails"></a>
595
596To 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).
597
598```js
599function openCamera(selection) {
600
601 var srcType = Camera.PictureSourceType.CAMERA;
602 var options = setOptions(srcType);
603 var func = createNewFileEntry;
604
605 if (selection == "camera-thmb") {
606 options.targetHeight = 100;
607 options.targetWidth = 100;
608 }
609
610 navigator.camera.getPicture(function cameraSuccess(imageUri) {
611
612 // Do something
613
614 }, function cameraError(error) {
615 console.debug("Unable to obtain picture: " + error, "app");
616
617 }, options);
618}
619```
620
621## Select a File from the Picture Library <a name="selectFile"></a>
622
623When 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.
624
625```js
626function openFilePicker(selection) {
627
628 var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
629 var options = setOptions(srcType);
630 var func = createNewFileEntry;
631
632 navigator.camera.getPicture(function cameraSuccess(imageUri) {
633
634 // Do something
635
636 }, function cameraError(error) {
637 console.debug("Unable to obtain picture: " + error, "app");
638
639 }, options);
640}
641```
642
643## Select an Image and Return Thumbnails (resized images) <a name="getFileThumbnails"></a>
644
645Resizing a file selected with the file picker works just like resizing using the Camera app; set the `targetHeight` and `targetWidth` options.
646
647```js
648function openFilePicker(selection) {
649
650 var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
651 var options = setOptions(srcType);
652 var func = createNewFileEntry;
653
654 if (selection == "picker-thmb") {
655 // To downscale a selected image,
656 // Camera.EncodingType (e.g., JPEG) must match the selected image type.
657 options.targetHeight = 100;
658 options.targetWidth = 100;
659 }
660
661 navigator.camera.getPicture(function cameraSuccess(imageUri) {
662
663 // Do something with image
664
665 }, function cameraError(error) {
666 console.debug("Unable to obtain picture: " + error, "app");
667
668 }, options);
669}
670```
671
672## Take a picture and get a FileEntry Object <a name="convert"></a>
673
674If 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).
675
676>*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`.
677
678Here 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.
679
680```js
681function getFileEntry(imgUri) {
682 window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
683
684 // Do something with the FileEntry object, like write to it, upload it, etc.
685 // writeFile(fileEntry, imgUri);
686 console.log("got file: " + fileEntry.fullPath);
687 // displayFileData(fileEntry.nativeURL, "Native URL");
688
689 }, function () {
690 // If don't get the FileEntry (which may happen when testing
691 // on some emulators), copy to a new FileEntry.
692 createNewFileEntry(imgUri);
693 });
694}
695```
696
697In 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.
698
699>*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file).
700
701The 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.
702
703```js
704function createNewFileEntry(imgUri) {
705 window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
706
707 // JPEG file
708 dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) {
709
710 // Do something with it, like write to it, upload it, etc.
711 // writeFile(fileEntry, imgUri);
712 console.log("got file: " + fileEntry.fullPath);
713 // displayFileData(fileEntry.fullPath, "File copied to");
714
715 }, onErrorCreateFile);
716
717 }, onErrorResolveUrl);
718}
719```