You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

793 lines
35 KiB

  1. ---
  2. title: Camera
  3. description: 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. |Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
  24. |:-:|:-:|:-:|:-:|:-:|:-:|:-:|
  25. |[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-4.4,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-5.1,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android-6.0,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-9.3,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios-10.0,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios-10.0,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)
  26. # cordova-plugin-camera
  27. This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from
  28. the system's image library.
  29. Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
  30. document.addEventListener("deviceready", onDeviceReady, false);
  31. function onDeviceReady() {
  32. console.log(navigator.camera);
  33. }
  34. ## Installation
  35. This requires cordova 5.0+
  36. cordova plugin add cordova-plugin-camera
  37. Older versions of cordova can still install via the __deprecated__ id
  38. cordova plugin add org.apache.cordova.camera
  39. It is also possible to install via repo url directly ( unstable )
  40. cordova plugin add https://github.com/apache/cordova-plugin-camera.git
  41. ## How to Contribute
  42. Contributors 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).
  43. There 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).
  44. :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).
  45. **Have a solution?** Send a [Pull Request](https://github.com/apache/cordova-plugin-camera/pulls).
  46. In 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).
  47. **And don't forget to test and document your code.**
  48. ## This documentation is generated by a tool
  49. :warning: Run `npm install` in the plugin repo to enable automatic docs generation if you plan to send a PR.
  50. [jsdoc-to-markdown](https://www.npmjs.com/package/jsdoc-to-markdown) is used to generate the docs.
  51. Documentation 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).
  52. ### iOS Quirks
  53. Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist.
  54. - `NSCameraUsageDescription` describes the reason that the app accesses the user’s camera.
  55. - `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library.
  56. When the system prompts the user to allow access, this string is displayed as part of the dialog box.
  57. To add this entry you can pass the following variables on plugin install.
  58. - `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription`
  59. - `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription`
  60. Example:
  61. cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
  62. If you don't pass the variable, the plugin will add an empty string as value.
  63. ---
  64. # API Reference <a name="reference"></a>
  65. * [camera](#module_camera)
  66. * [.getPicture(successCallback, errorCallback, options)](#module_camera.getPicture)
  67. * [.cleanup()](#module_camera.cleanup)
  68. * [.onError](#module_camera.onError) : <code>function</code>
  69. * [.onSuccess](#module_camera.onSuccess) : <code>function</code>
  70. * [.CameraOptions](#module_camera.CameraOptions) : <code>Object</code>
  71. * [Camera](#module_Camera)
  72. * [.DestinationType](#module_Camera.DestinationType) : <code>enum</code>
  73. * [.EncodingType](#module_Camera.EncodingType) : <code>enum</code>
  74. * [.MediaType](#module_Camera.MediaType) : <code>enum</code>
  75. * [.PictureSourceType](#module_Camera.PictureSourceType) : <code>enum</code>
  76. * [.PopoverArrowDirection](#module_Camera.PopoverArrowDirection) : <code>enum</code>
  77. * [.Direction](#module_Camera.Direction) : <code>enum</code>
  78. * [CameraPopoverHandle](#module_CameraPopoverHandle)
  79. * [CameraPopoverOptions](#module_CameraPopoverOptions)
  80. ---
  81. <a name="module_camera"></a>
  82. ## camera
  83. <a name="module_camera.getPicture"></a>
  84. ### camera.getPicture(successCallback, errorCallback, options)
  85. Takes a photo using the camera, or retrieves a photo from the device's
  86. image gallery. The image is passed to the success callback as a
  87. Base64-encoded `String`, or as the URI for the image file.
  88. The `camera.getPicture` function opens the device's default camera
  89. application that allows users to snap pictures by default - this behavior occurs,
  90. when `Camera.sourceType` equals [`Camera.PictureSourceType.CAMERA`](#module_Camera.PictureSourceType).
  91. Once the user snaps the photo, the camera application closes and the application is restored.
  92. If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or
  93. `Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays
  94. that allows users to select an existing image.
  95. The return value is sent to the [`cameraSuccess`](#module_camera.onSuccess) callback function, in
  96. one of the following formats, depending on the specified
  97. `cameraOptions`:
  98. - A `String` containing the Base64-encoded photo image.
  99. - A `String` representing the image file location on local storage (default).
  100. You can do whatever you want with the encoded image or URI, for
  101. example:
  102. - Render the image in an `<img>` tag, as in the example below
  103. - Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
  104. - Post the data to a remote server
  105. __NOTE__: Photo resolution on newer devices is quite good. Photos
  106. selected from the device's gallery are not downscaled to a lower
  107. quality, even if a `quality` parameter is specified. To avoid common
  108. memory problems, set `Camera.destinationType` to `FILE_URI` rather
  109. than `DATA_URL`.
  110. __Supported Platforms__
  111. - Android
  112. - BlackBerry
  113. - Browser
  114. - Firefox
  115. - FireOS
  116. - iOS
  117. - Windows
  118. - WP8
  119. - Ubuntu
  120. More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).
  121. **Kind**: static method of <code>[camera](#module_camera)</code>
  122. | Param | Type | Description |
  123. | --- | --- | --- |
  124. | successCallback | <code>[onSuccess](#module_camera.onSuccess)</code> | |
  125. | errorCallback | <code>[onError](#module_camera.onError)</code> | |
  126. | options | <code>[CameraOptions](#module_camera.CameraOptions)</code> | CameraOptions |
  127. **Example**
  128. ```js
  129. navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
  130. ```
  131. <a name="module_camera.cleanup"></a>
  132. ### camera.cleanup()
  133. Removes intermediate image files that are kept in temporary storage
  134. after calling [`camera.getPicture`](#module_camera.getPicture). Applies only when the value of
  135. `Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the
  136. `Camera.destinationType` equals `Camera.DestinationType.FILE_URI`.
  137. __Supported Platforms__
  138. - iOS
  139. **Kind**: static method of <code>[camera](#module_camera)</code>
  140. **Example**
  141. ```js
  142. navigator.camera.cleanup(onSuccess, onFail);
  143. function onSuccess() {
  144. console.log("Camera cleanup success.")
  145. }
  146. function onFail(message) {
  147. alert('Failed because: ' + message);
  148. }
  149. ```
  150. <a name="module_camera.onError"></a>
  151. ### camera.onError : <code>function</code>
  152. Callback function that provides an error message.
  153. **Kind**: static typedef of <code>[camera](#module_camera)</code>
  154. | Param | Type | Description |
  155. | --- | --- | --- |
  156. | message | <code>string</code> | The message is provided by the device's native code. |
  157. <a name="module_camera.onSuccess"></a>
  158. ### camera.onSuccess : <code>function</code>
  159. Callback function that provides the image data.
  160. **Kind**: static typedef of <code>[camera](#module_camera)</code>
  161. | Param | Type | Description |
  162. | --- | --- | --- |
  163. | imageData | <code>string</code> | Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`](#module_camera.CameraOptions) in effect. |
  164. **Example**
  165. ```js
  166. // Show image
  167. //
  168. function cameraCallback(imageData) {
  169. var image = document.getElementById('myImage');
  170. image.src = "data:image/jpeg;base64," + imageData;
  171. }
  172. ```
  173. <a name="module_camera.CameraOptions"></a>
  174. ### camera.CameraOptions : <code>Object</code>
  175. Optional parameters to customize the camera settings.
  176. * [Quirks](#CameraOptions-quirks)
  177. **Kind**: static typedef of <code>[camera](#module_camera)</code>
  178. **Properties**
  179. | Name | Type | Default | Description |
  180. | --- | --- | --- | --- |
  181. | 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.) |
  182. | destinationType | <code>[DestinationType](#module_Camera.DestinationType)</code> | <code>FILE_URI</code> | Choose the format of the return value. |
  183. | sourceType | <code>[PictureSourceType](#module_Camera.PictureSourceType)</code> | <code>CAMERA</code> | Set the source of the picture. |
  184. | allowEdit | <code>Boolean</code> | <code>true</code> | Allow simple editing of image before selection. |
  185. | encodingType | <code>[EncodingType](#module_Camera.EncodingType)</code> | <code>JPEG</code> | Choose the returned image file's encoding. |
  186. | targetWidth | <code>number</code> | | Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant. |
  187. | targetHeight | <code>number</code> | | Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant. |
  188. | 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`. |
  189. | correctOrientation | <code>Boolean</code> | | Rotate the image to correct for the orientation of the device during capture. |
  190. | saveToPhotoAlbum | <code>Boolean</code> | | Save the image to the photo album on the device after capture. |
  191. | popoverOptions | <code>[CameraPopoverOptions](#module_CameraPopoverOptions)</code> | | iOS-only options that specify popover location in iPad. |
  192. | cameraDirection | <code>[Direction](#module_Camera.Direction)</code> | <code>BACK</code> | Choose the camera to use (front- or back-facing). |
  193. ---
  194. <a name="module_Camera"></a>
  195. ## Camera
  196. <a name="module_Camera.DestinationType"></a>
  197. ### Camera.DestinationType : <code>enum</code>
  198. Defines the output format of `Camera.getPicture` call.
  199. _Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
  200. `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
  201. disable any image modifications (resize, quality change, cropping, etc.) due
  202. to implementation specific.
  203. **Kind**: static enum property of <code>[Camera](#module_Camera)</code>
  204. **Properties**
  205. | Name | Type | Default | Description |
  206. | --- | --- | --- | --- |
  207. | 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 |
  208. | FILE_URI | <code>number</code> | <code>1</code> | Return file uri (content://media/external/images/media/2 for Android) |
  209. | NATIVE_URI | <code>number</code> | <code>2</code> | Return native uri (eg. asset-library://... for iOS) |
  210. <a name="module_Camera.EncodingType"></a>
  211. ### Camera.EncodingType : <code>enum</code>
  212. **Kind**: static enum property of <code>[Camera](#module_Camera)</code>
  213. **Properties**
  214. | Name | Type | Default | Description |
  215. | --- | --- | --- | --- |
  216. | JPEG | <code>number</code> | <code>0</code> | Return JPEG encoded image |
  217. | PNG | <code>number</code> | <code>1</code> | Return PNG encoded image |
  218. <a name="module_Camera.MediaType"></a>
  219. ### Camera.MediaType : <code>enum</code>
  220. **Kind**: static enum property of <code>[Camera](#module_Camera)</code>
  221. **Properties**
  222. | Name | Type | Default | Description |
  223. | --- | --- | --- | --- |
  224. | PICTURE | <code>number</code> | <code>0</code> | Allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType |
  225. | VIDEO | <code>number</code> | <code>1</code> | Allow selection of video only, ONLY RETURNS URL |
  226. | ALLMEDIA | <code>number</code> | <code>2</code> | Allow selection from all media types |
  227. <a name="module_Camera.PictureSourceType"></a>
  228. ### Camera.PictureSourceType : <code>enum</code>
  229. Defines the output format of `Camera.getPicture` call.
  230. _Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
  231. along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
  232. change, cropping, etc.) due to implementation specific.
  233. **Kind**: static enum property of <code>[Camera](#module_Camera)</code>
  234. **Properties**
  235. | Name | Type | Default | Description |
  236. | --- | --- | --- | --- |
  237. | PHOTOLIBRARY | <code>number</code> | <code>0</code> | Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) |
  238. | CAMERA | <code>number</code> | <code>1</code> | Take picture from camera |
  239. | SAVEDPHOTOALBUM | <code>number</code> | <code>2</code> | Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) |
  240. <a name="module_Camera.PopoverArrowDirection"></a>
  241. ### Camera.PopoverArrowDirection : <code>enum</code>
  242. Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
  243. **Kind**: static enum property of <code>[Camera](#module_Camera)</code>
  244. **Properties**
  245. | Name | Type | Default |
  246. | --- | --- | --- |
  247. | ARROW_UP | <code>number</code> | <code>1</code> |
  248. | ARROW_DOWN | <code>number</code> | <code>2</code> |
  249. | ARROW_LEFT | <code>number</code> | <code>4</code> |
  250. | ARROW_RIGHT | <code>number</code> | <code>8</code> |
  251. | ARROW_ANY | <code>number</code> | <code>15</code> |
  252. <a name="module_Camera.Direction"></a>
  253. ### Camera.Direction : <code>enum</code>
  254. **Kind**: static enum property of <code>[Camera](#module_Camera)</code>
  255. **Properties**
  256. | Name | Type | Default | Description |
  257. | --- | --- | --- | --- |
  258. | BACK | <code>number</code> | <code>0</code> | Use the back-facing camera |
  259. | FRONT | <code>number</code> | <code>1</code> | Use the front-facing camera |
  260. ---
  261. <a name="module_CameraPopoverOptions"></a>
  262. ## CameraPopoverOptions
  263. iOS-only parameters that specify the anchor element location and arrow
  264. direction of the popover when selecting images from an iPad's library
  265. or album.
  266. Note that the size of the popover may change to adjust to the
  267. direction of the arrow and orientation of the screen. Make sure to
  268. account for orientation changes when specifying the anchor element
  269. location.
  270. | Param | Type | Default | Description |
  271. | --- | --- | --- | --- |
  272. | [x] | <code>Number</code> | <code>0</code> | x pixel coordinate of screen element onto which to anchor the popover. |
  273. | [y] | <code>Number</code> | <code>32</code> | y pixel coordinate of screen element onto which to anchor the popover. |
  274. | [width] | <code>Number</code> | <code>320</code> | width, in pixels, of the screen element onto which to anchor the popover. |
  275. | [height] | <code>Number</code> | <code>480</code> | height, in pixels, of the screen element onto which to anchor the popover. |
  276. | [arrowDir] | <code>[PopoverArrowDirection](#module_Camera.PopoverArrowDirection)</code> | <code>ARROW_ANY</code> | Direction the arrow on the popover should point. |
  277. ---
  278. <a name="module_CameraPopoverHandle"></a>
  279. ## CameraPopoverHandle
  280. A handle to an image picker popover.
  281. __Supported Platforms__
  282. - iOS
  283. **Example**
  284. ```js
  285. navigator.camera.getPicture(onSuccess, onFail,
  286. {
  287. destinationType: Camera.DestinationType.FILE_URI,
  288. sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
  289. popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
  290. });
  291. // Reposition the popover if the orientation changes.
  292. window.onorientationchange = function() {
  293. var cameraPopoverHandle = new CameraPopoverHandle();
  294. var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
  295. cameraPopoverHandle.setPosition(cameraPopoverOptions);
  296. }
  297. ```
  298. ---
  299. ## `camera.getPicture` Errata
  300. #### Example <a name="camera-getPicture-examples"></a>
  301. Take a photo and retrieve the image's file location:
  302. navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
  303. destinationType: Camera.DestinationType.FILE_URI });
  304. function onSuccess(imageURI) {
  305. var image = document.getElementById('myImage');
  306. image.src = imageURI;
  307. }
  308. function onFail(message) {
  309. alert('Failed because: ' + message);
  310. }
  311. Take a photo and retrieve it as a Base64-encoded image:
  312. /**
  313. * Warning: Using DATA_URL is not recommended! The DATA_URL destination
  314. * type is very memory intensive, even with a low quality setting. Using it
  315. * can result in out of memory errors and application crashes. Use FILE_URI
  316. * or NATIVE_URI instead.
  317. */
  318. navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
  319. destinationType: Camera.DestinationType.DATA_URL
  320. });
  321. function onSuccess(imageData) {
  322. var image = document.getElementById('myImage');
  323. image.src = "data:image/jpeg;base64," + imageData;
  324. }
  325. function onFail(message) {
  326. alert('Failed because: ' + message);
  327. }
  328. #### Preferences (iOS)
  329. - __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.
  330. <preference name="CameraUsesGeolocation" value="false" />
  331. #### Amazon Fire OS Quirks <a name="camera-getPicture-quirks"></a>
  332. Amazon Fire OS uses intents to launch the camera activity on the device to capture
  333. images, and on phones with low memory, the Cordova activity may be killed. In this
  334. scenario, the image may not appear when the Cordova activity is restored.
  335. #### Android Quirks
  336. Android uses intents to launch the camera activity on the device to capture
  337. images, and on phones with low memory, the Cordova activity may be killed. In this
  338. scenario, the result from the plugin call will be delivered via the resume event.
  339. See [the Android Lifecycle guide][android_lifecycle]
  340. for more information. The `pendingResult.result` value will contain the value that
  341. would be passed to the callbacks (either the URI/URL or an error message). Check
  342. the `pendingResult.pluginStatus` to determine whether or not the call was
  343. successful.
  344. #### Browser Quirks
  345. Can only return photos as Base64-encoded image.
  346. #### Firefox OS Quirks
  347. Camera plugin is currently implemented using [Web Activities][web_activities].
  348. #### iOS Quirks
  349. Including a JavaScript `alert()` in either of the callback functions
  350. can cause problems. Wrap the alert within a `setTimeout()` to allow
  351. the iOS image picker or popover to fully close before the alert
  352. displays:
  353. setTimeout(function() {
  354. // do your thing here!
  355. }, 0);
  356. #### Windows Phone 7 Quirks
  357. Invoking the native camera application while the device is connected
  358. via Zune does not work, and triggers an error callback.
  359. #### Windows quirks
  360. On Windows Phone 8.1 using `SAVEDPHOTOALBUM` or `PHOTOLIBRARY` as a source type causes application to suspend until file picker returns the selected image and
  361. then 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
  362. start page from scratch and success and error callbacks will never be called.
  363. To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page.
  364. More 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)
  365. #### Tizen Quirks
  366. Tizen only supports a `destinationType` of
  367. `Camera.DestinationType.FILE_URI` and a `sourceType` of
  368. `Camera.PictureSourceType.PHOTOLIBRARY`.
  369. ## `CameraOptions` Errata <a name="CameraOptions-quirks"></a>
  370. #### Amazon Fire OS Quirks
  371. - Any `cameraDirection` value results in a back-facing photo.
  372. - Ignores the `allowEdit` parameter.
  373. - `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
  374. #### Android Quirks
  375. - Any `cameraDirection` value results in a back-facing photo.
  376. - **`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.
  377. - `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
  378. - 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.
  379. #### BlackBerry 10 Quirks
  380. - Ignores the `quality` parameter.
  381. - Ignores the `allowEdit` parameter.
  382. - `Camera.MediaType` is not supported.
  383. - Ignores the `correctOrientation` parameter.
  384. - Ignores the `cameraDirection` parameter.
  385. #### Firefox OS Quirks
  386. - Ignores the `quality` parameter.
  387. - `Camera.DestinationType` is ignored and equals `1` (image file URI)
  388. - Ignores the `allowEdit` parameter.
  389. - Ignores the `PictureSourceType` parameter (user chooses it in a dialog window)
  390. - Ignores the `encodingType`
  391. - Ignores the `targetWidth` and `targetHeight`
  392. - `Camera.MediaType` is not supported.
  393. - Ignores the `correctOrientation` parameter.
  394. - Ignores the `cameraDirection` parameter.
  395. #### iOS Quirks
  396. - 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.
  397. - When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter.
  398. - When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture.
  399. #### Tizen Quirks
  400. - options not supported
  401. - always returns a FILE URI
  402. #### Windows Phone 7 and 8 Quirks
  403. - Ignores the `allowEdit` parameter.
  404. - Ignores the `correctOrientation` parameter.
  405. - Ignores the `cameraDirection` parameter.
  406. - 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].
  407. - Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.
  408. [android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html
  409. [web_activities]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
  410. [wp8_bug]: https://issues.apache.org/jira/browse/CB-2083
  411. [msdn_wp8_docs]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx
  412. ## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails <a name="sample"></a>
  413. The 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:
  414. * Open the Camera app and [take a Picture](#takePicture)
  415. * Take a picture and [return thumbnails](#getThumbnails) (resized picture)
  416. * Take a picture and [generate a FileEntry object](#convert)
  417. * [Select a file](#selectFile) from the picture library
  418. * Select a JPEG image and [return thumbnails](#getFileThumbnails) (resized image)
  419. * Select an image and [generate a FileEntry object](#convert)
  420. ## Take a Picture <a name="takePicture"></a>
  421. Before 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.
  422. ```js
  423. function setOptions(srcType) {
  424. var options = {
  425. // Some common settings are 20, 50, and 100
  426. quality: 50,
  427. destinationType: Camera.DestinationType.FILE_URI,
  428. // In this app, dynamically set the picture source, Camera or photo gallery
  429. sourceType: srcType,
  430. encodingType: Camera.EncodingType.JPEG,
  431. mediaType: Camera.MediaType.PICTURE,
  432. allowEdit: true,
  433. correctOrientation: true //Corrects Android orientation quirks
  434. }
  435. return options;
  436. }
  437. ```
  438. Typically, 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.
  439. You 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.
  440. ```js
  441. function openCamera(selection) {
  442. var srcType = Camera.PictureSourceType.CAMERA;
  443. var options = setOptions(srcType);
  444. var func = createNewFileEntry;
  445. navigator.camera.getPicture(function cameraSuccess(imageUri) {
  446. displayImage(imageUri);
  447. // You may choose to copy the picture, save it somewhere, or upload.
  448. func(imageUri);
  449. }, function cameraError(error) {
  450. console.debug("Unable to obtain picture: " + error, "app");
  451. }, options);
  452. }
  453. ```
  454. Once 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.
  455. ```js
  456. function displayImage(imgUri) {
  457. var elem = document.getElementById('imageFile');
  458. elem.src = imgUri;
  459. }
  460. ```
  461. To 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.
  462. ```html
  463. <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 *">
  464. ```
  465. ## Take a Picture and Return Thumbnails (Resize the Picture) <a name="getThumbnails"></a>
  466. To 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).
  467. ```js
  468. function openCamera(selection) {
  469. var srcType = Camera.PictureSourceType.CAMERA;
  470. var options = setOptions(srcType);
  471. var func = createNewFileEntry;
  472. if (selection == "camera-thmb") {
  473. options.targetHeight = 100;
  474. options.targetWidth = 100;
  475. }
  476. navigator.camera.getPicture(function cameraSuccess(imageUri) {
  477. // Do something
  478. }, function cameraError(error) {
  479. console.debug("Unable to obtain picture: " + error, "app");
  480. }, options);
  481. }
  482. ```
  483. ## Select a File from the Picture Library <a name="selectFile"></a>
  484. When 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.
  485. ```js
  486. function openFilePicker(selection) {
  487. var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
  488. var options = setOptions(srcType);
  489. var func = createNewFileEntry;
  490. navigator.camera.getPicture(function cameraSuccess(imageUri) {
  491. // Do something
  492. }, function cameraError(error) {
  493. console.debug("Unable to obtain picture: " + error, "app");
  494. }, options);
  495. }
  496. ```
  497. ## Select an Image and Return Thumbnails (resized images) <a name="getFileThumbnails"></a>
  498. Resizing a file selected with the file picker works just like resizing using the Camera app; set the `targetHeight` and `targetWidth` options.
  499. ```js
  500. function openFilePicker(selection) {
  501. var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
  502. var options = setOptions(srcType);
  503. var func = createNewFileEntry;
  504. if (selection == "picker-thmb") {
  505. // To downscale a selected image,
  506. // Camera.EncodingType (e.g., JPEG) must match the selected image type.
  507. options.targetHeight = 100;
  508. options.targetWidth = 100;
  509. }
  510. navigator.camera.getPicture(function cameraSuccess(imageUri) {
  511. // Do something with image
  512. }, function cameraError(error) {
  513. console.debug("Unable to obtain picture: " + error, "app");
  514. }, options);
  515. }
  516. ```
  517. ## Take a picture and get a FileEntry Object <a name="convert"></a>
  518. If 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).
  519. >*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`.
  520. Here 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.
  521. ```js
  522. function getFileEntry(imgUri) {
  523. window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
  524. // Do something with the FileEntry object, like write to it, upload it, etc.
  525. // writeFile(fileEntry, imgUri);
  526. console.log("got file: " + fileEntry.fullPath);
  527. // displayFileData(fileEntry.nativeURL, "Native URL");
  528. }, function () {
  529. // If don't get the FileEntry (which may happen when testing
  530. // on some emulators), copy to a new FileEntry.
  531. createNewFileEntry(imgUri);
  532. });
  533. }
  534. ```
  535. In 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.
  536. >*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file).
  537. The 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.
  538. ```js
  539. function createNewFileEntry(imgUri) {
  540. window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
  541. // JPEG file
  542. dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) {
  543. // Do something with it, like write to it, upload it, etc.
  544. // writeFile(fileEntry, imgUri);
  545. console.log("got file: " + fileEntry.fullPath);
  546. // displayFileData(fileEntry.fullPath, "File copied to");
  547. }, onErrorCreateFile);
  548. }, onErrorResolveUrl);
  549. }
  550. ```