Compare commits

...

214 Commits

Author SHA1 Message Date
Manuel Beck
90ad137398 fix(ios)! remove iPadOS popover code (#941)
- On iPadOS it was possible to configure a popover for setting the position, width and arrow position of the popover.  The code used the deprecated `UIPopoverController`, which would have to be fixed. To keep the plugin also maintainable, this was removed.
- The popover could repositioned with a `CameraPopoverHandle` on a `window.onorientationchange`. This was removed also.
- Removed documentation for popover from `README.md`
2026-01-15 17:26:37 +01:00
Manuel Beck
dc682b2532 feat(ios): use PHPickerViewController for iOS 14+ (#937)
- Does not need any permissions for reading images
- The PHPickerViewController class is an alternative to UIImagePickerController. PHPickerViewController improves stability and reliability, and includes several benefits to developers and users, such as the following:
- Deferred image loading and recovery UI
- Reliable handling of large and complex assets, like RAW and panoramic images
- User-selectable assets that aren’t available for UIImagePickerController
- Configuration of the picker to display only Live Photos
- Availability of PHLivePhoto objects without library access
- Stricter validations against invalid inputs
- See documentation of PHPickerViewController: https://developer.apple.com/documentation/photosui/phpickerviewcontroller?language=objc
- Added tests for PHPickerViewController in `CameraTest.m`

* Documentation and formatting

- Document `takePicture` and `showCameraPicker` in `CDVCamera.m`
- A pragmas for UIImagePickerControllerDelegate methods and CLLocationManager methods
- Format some long methods declarations to multi-line instead single-line for better readability
- Remove unnecessry `dispatch_async(dispatch_get_main_queue() ...` in `takePicture` before calling `showCameraPicker`. This is already done in `showCameraPicker`.
- Source out code for permission denied alert dialog when accessing the camera or UIImagePickerController on iOS < 14 for picking images

* feat(ios): proper formatting of methods

- Use linux brace style: A brace have to be on a new line for method declarations
- Remove unnecessary whitespaces in method declrations

* doc: readme update

- Better document usage descriptions
- `NSPhotoLibraryUsageDescription` not needed for iOS 14+ when only picking images
- Improve formatting for xml, js
- sourceType `SAVEDPHOTOALBUM` is the same as `PHOTOLIBRARY` on Android and iOS 14+
- Use `PHOTOLIBRARY` as sourceType instead of `SAVEDPHOTOALBUM` in  photo picker example

* Android: Document `SAVEDPHOTOALBUM``

- Make clear that `SAVEDPHOTOALBUM` is the same like `PHOTOLIBRARY` and has only an effect on iOS < 14
- Format code when creating image chooser and document the request code parameter
2026-01-13 08:33:59 +01:00
Manuel Beck
599954887b chore(ci): update obsolete XCode versions, add iOS 18 and 26 (#938)
- XCode 13 and 14 is not available anymore, replaced it with XCode 15
- Added tests for iOS 18 and 26
2026-01-12 15:43:09 +01:00
Manuel Beck
80a2f18a05 chore!: bump 9.0.0-dev and cordova-ios to 7.0.0 (#939)
- Increased cordova-ios version to 7.x to make newer features availabe
- Removed wrong cordovaDependency for `5.0.4-dev`. `cordovaDependencies` matches only against npm released versions.
2025-12-08 16:32:50 +01:00
Norman Breau
8864262022 fix(android): Error propagation when no Camera application is available (#926) 2025-03-20 16:13:02 -03:00
エリス
b002b48735 chore: remove trailing whitespace (#921) 2025-01-15 16:03:14 +09:00
Norman Breau
979155ee98 chore: 8.0.1-dev 2024-10-30 11:12:59 -03:00
Norman Breau
7f33ef4add chore: version 8.0.0 2024-10-30 11:08:58 -03:00
Norman Breau
4c9dc10512 deprecation: allowEdit (#914)
* deprecation: allowEdit

* applied suggestions to verbiage
2024-10-30 09:48:20 -03:00
Norman Breau
de468b6f63 fix: Remove WRITE_EXTERNAL_PERMISSION (#915) 2024-10-29 01:15:50 -03:00
Norman Breau
48c4cdd47f refactor(android): Make WRITE_EXTERNAL_STORAGE optional (#909)
* refactor(android): Rework permission management to make WRITE_EXTERNAL_STORAGE optional

* removed unused getPermissions API

* Proper error if WRITE_EXTERNAL_STORAGE is required but missing the declaration

* removed obsolete hasPermissions API
2024-10-28 15:21:37 -03:00
Norman Breau
7d159cf3c9 docs: Revisions for v8 public API changes with the return string formats of getPicture (#913) 2024-10-28 14:01:04 -03:00
Norman Breau
c208754c08 refactor(android): remove query img usage (#907)
* refactor: remove unnecessary duplicate image checks and queryImgDb usage

* remove unused imageType parameter, because it's a private API anyway
2024-10-28 13:32:35 -03:00
Norman Breau
0d86764b90 refactor(android): replace image path usage with image uris (#906)
* refactor(android): clean up image file path usages

* removed references of image paths in log messages
2024-10-28 12:35:50 -03:00
Norman Breau
7adccc8ee9 fix(ios): Sync camera API return to match Android changes (#911) 2024-10-27 08:32:38 -03:00
Norman Breau
53795454f4 fix(browser): Make data uri be returned as actual URI strings (#912) 2024-10-27 08:32:14 -03:00
Norman Breau
2eaa9a3972 fix: return content uris when possible when selecting from gallery (#902) 2024-10-26 00:58:24 -03:00
Norman Breau
a672c31efb fix(android): Return data uris as an URI (#910) 2024-10-26 00:58:00 -03:00
Norman Breau
16325102c7 fix(android): Improper serialization of image uri in save instance state (#903) 2024-10-25 13:59:29 -03:00
Norman Breau
36bf8e7331 fix(android): improper cache path construction during image manipulation (#905) 2024-10-25 13:15:59 -03:00
Norman Breau
feb7643bc3 fix(android): Use VERSION_CODES instead of hard-coded API literals (#904) 2024-10-25 13:10:05 -03:00
Norman Breau
44480300d9 fix(android): Isolate provider access to a subdirectory (#901) 2024-10-25 13:09:03 -03:00
ravi-yk
faa4615ee0 Remove media permissions to make complaint with Android 14 requirements (#889)
Co-authored-by: Ravi Yakasiri <ravi.yakasiri@planonsoftware.com>
2024-10-24 13:38:18 -03:00
Norman Breau
0a4bfe1a74 chore: Update package to 8.0.0-dev (#899) 2024-10-21 09:38:35 -03:00
Norman Breau
49438dee6d chore: Update eslint config to 5.1.0 (#898) 2024-10-19 12:17:43 -03:00
jcesarmobile
f38aba2b59 ci: sync workflow with paramedic (#895) 2024-08-08 12:16:56 +09:00
Norman Breau
3b73186b91 chore: Added npmrc 2024-07-27 01:30:29 -03:00
Norman Breau
40a5db10c7 ci(android): Update Android CI to be compatible with cordova-android@13 (#890) 2024-07-16 14:54:17 -03:00
Erisu
9eecbaa1af chore: bump version 7.0.1-dev 2023-09-06 17:02:23 +09:00
Erisu
24839eb71f release(camera-v7.0.0): updated version and RELEASENOTES.md 2023-09-06 16:55:23 +09:00
エリス
64bd32d641 ci(gh-action): sync with paramedic configs (#851) 2023-09-06 02:27:41 +09:00
jcesarmobile
0796f784c1 chore: remove windows/osx from plugin.xml (#850) 2023-09-01 02:12:00 +02:00
jcesarmobile
20293f3d64 fix!: remove deprecated platforms (#848) 2023-09-01 00:34:30 +02:00
jcesarmobile
8cb34e1175 chore: Update SUPPORT_QUESTION.md template (#849) 2023-08-30 23:35:39 +02:00
エリス
505ccefb4c feat(android)!: Android 13 support (#844)
* feat(android)!: Android 13 support
* refactor(android): simplify getPermissions logic
* feat(android)!: bump cordova-android requirement to >=12.0.0
* feat(android): update saveAlbumPermission to include Android 9 and below use case

---------

Co-authored-by: ochakov <evgeny@ochakov.com>
2023-08-26 20:21:32 +09:00
エリス
61a6e9bb44 dep(dev)!: bump @cordova/eslint-config@5.0.0 (#846)
* dep(dev)!: bump @cordova/eslint-config@5.0.0
* chore: apply automatic lint fix
2023-08-18 00:59:25 +09:00
エリス
c2eb21d201 chore: bump plugin version 7.0.0-dev (#845) 2023-08-17 21:43:13 +09:00
Norman Breau
23642f09b5 ci(android): Drop API 22 & 31. Added API 24 & 33 (#835)
Co-authored-by: エリス <erisu@users.noreply.github.com>
2023-06-05 22:50:49 +09:00
Norman Breau
84166f6355 chore(android): Cleanup obsolete BuildConfig comments (#831) 2023-04-14 08:48:12 -03:00
seamlink-aalves
2c09ade500 fix(android): set applicationId (#827)
Co-authored-by: Alexandre Alves <aalves@seamlink.com>
2023-04-14 08:06:30 -03:00
エリス
827bb611ee ci: sync workflow with paramedic (#804) 2022-10-01 13:28:27 +09:00
jcesarmobile
d0545c879f fix(browser): use navigator.mediaDevices.getUserMedia (#810) 2022-09-30 00:59:27 +02:00
jcesarmobile
d0d46c151c docs(README): Document ANDROIDX_CORE_VERSION variable (#808) 2022-09-25 05:03:51 +02:00
エリス
a18fda7ddf dep(npm): bump package-lock v2 w/ rebuild (#800) 2022-08-10 16:49:43 +09:00
エリス
3e548770b7 ci(android): update java requirement for cordova-android@11 (#798) 2022-07-17 13:30:47 +09:00
Scott Murphy
4608f8ef80 fix(ios): preserving EXIF data (#712) 2022-03-22 16:23:56 +09:00
Marcus Abrahamsson
53223c3df2 fix(android): update queries in plugin.xml (#780)
Solves the issue with duplicate queries elements in AppManifest.xml

https://github.com/apache/cordova-plugin-camera/issues/779
2022-03-18 09:08:13 +09:00
エリス
bf12b39d18 ci(ios): update workflow w/ iOS 15 (#770) 2021-10-18 21:13:02 +09:00
エリス
ed216ce714 ci: remove old ci workflow (#766) 2021-09-25 16:02:04 +09:00
エリス
879712028a ci: add action-badge (#765) 2021-09-25 01:04:05 +09:00
エリス
204234b1b9 ci: remove travis & appveyor (#764) 2021-09-25 00:07:07 +09:00
エリス
0fba37cac3 ci: add gh-actions workflows (#762) 2021-09-16 22:17:11 +09:00
Erisu
5b8263732a Increment package version to 6.0.1-dev 2021-08-23 14:25:23 +09:00
Erisu
869f02da1a Updated version and RELEASENOTES.md for release 6.0.0 (camera-v6.0.0) 2021-08-19 17:14:44 +09:00
Dave Alden
e9db20e381 fix(android): return exception message (where it exists) (#687)
Co-authored-by: エリス <erisu@users.noreply.github.com>
Co-authored-by: jcesarmobile <jcesarmobile@gmail.com>
2021-08-11 16:56:42 +09:00
Francis
c7971d9f63 fix(android): file path correction if Uri authority is FileProvider (#585)
Co-authored-by: Tim Brust <ratchet.player@gmx.de>
Co-authored-by: Francis Monier <contactpro@francismonier.com>
Co-authored-by: Norman Breau <norman@normanbreau.com>
2021-08-11 16:34:20 +09:00
Niklas Merz
3112e5fb15 chore: add release notify action (#654)
Co-authored-by: Erisu <ellis.bryan@gmail.com>
2021-08-11 16:04:14 +09:00
Jesse MacFadyen
c56a255fe8 ci(gh-action): added workflow to run tests (#745)
Co-authored-by: Erisu <ellis.bryan@gmail.com>
2021-08-11 16:03:34 +09:00
エリス
0227cdcf14 feat(android)!: support AndroidX (#751)
* feat: migrate FileProvider to androidx
* feat: add androidx.core:core with variable override ANDROIDX_CORE_VERSION
2021-08-09 23:09:29 +09:00
Pieter Van Poyer
75bf807261 Bugfix issue 711 heic format (#731)
* Android - issue/711 - support .heic format
2021-08-09 15:36:58 +02:00
エリス
abfbbd35d5 fix(android): supports sdk-30 package visibility (#684) 2021-08-09 20:57:12 +09:00
エリス
59cf76d1da feat: bump cordova-android requirements for 10.x (#750) 2021-08-09 20:56:15 +09:00
エリス
4ee90a84f3 feat: bump plugin version for next major (#749)
Co-authored-by: Niklas Merz <nmerz@gedys-intraware.de>
2021-08-09 20:52:50 +09:00
Niklas Merz
5587bec320 Bump 5.0.4-dev 2021-08-09 10:53:00 +02:00
Erisu
d523142cf2 Updated version and RELEASENOTES.md for release 5.0.3 (camera-v5.0.3) 2021-08-04 13:16:27 +09:00
エリス
0f6435ec73 chore: rebuilt package-lock.json (#754) 2021-08-04 13:06:29 +09:00
エリス
e81e02b21f fix: incorrect version in package-lock (#748) 2021-07-28 14:31:19 +09:00
エリス
1e20a9bd07 chore: set the 5.x versions locked to cordova-android <10.0.0 (#747) 2021-07-28 14:30:17 +09:00
Niklas Merz
d356030070 chore(asf): Update GitHub repo metadata (#729) 2021-06-28 11:16:24 +02:00
PVPoyer
7bc311fba9 Incremented plugin version. (cordova-plugin-camera20210511) 2021-05-11 22:45:53 +02:00
PVPoyer
e419a74546 Updated version and RELEASENOTES.md for release 5.0.2 (cordova-plugin-camera20210511) 2021-05-11 22:12:25 +02:00
Pieter Van Poyer
9a47f5c791 Merge pull request #728 from PieterVanPoyer/tasks/v5.0.2-audit-fix
chore(npm): fix npm audit issues automatically
2021-05-11 21:51:53 +02:00
PVPoyer
66d3f03270 plugin release preparation - audit fix 2021-05-11 21:39:28 +02:00
Pieter Van Poyer
731c10f5b2 Merge branch 'apache:master' into master 2021-05-11 21:32:47 +02:00
Pieter Van Poyer
f704689200 Bugfix issue 665 (#700)
* GH-665 - store the imageFilePath when the app is paused (onSaveInstance) and restore it back.

* Update src/android/CameraLauncher.java whitespace layout

Co-authored-by: Tim Brust <github@timbrust.de>

Co-authored-by: Tim Brust <github@timbrust.de>
2021-02-02 14:43:26 -04:00
Pieter Van Poyer
2bad1fd81c Merge pull request #1 from apache/master
make even
2021-01-08 17:14:07 +01:00
エリス
b43c78b419 ci: add node-14.x to workflow (#691) 2020-11-28 17:12:32 +09:00
Erisu
db2ffedecc Increment package version to 5.0.2-dev 2020-11-09 18:15:06 +09:00
Erisu
0d13b71d33 Updated version and RELEASENOTES.md for release 5.0.1 (camera-20201104) 2020-11-04 10:24:25 +09:00
エリス
8975171d7a chore(android): add missing apache license header (#686) 2020-11-04 10:12:19 +09:00
jcesarmobile
2d1ee66a2b fix(ios): correctly append exif on iOS 14 (#685) 2020-10-28 18:47:10 +01:00
Pieter Van Poyer
ebe0517a24 Bugfix issue 341 save to photo gallery - Fixes #341, fixes #577 (#669)
* GH-341 - GH-577 Fixed the Save Photo To Album starting from camera - Android

- saveToPhotoAlbum feature fixed by taken into count content - uri. (writeUncompressedImage method) ( see: https://github.com/apache/cordova-plugin-camera/issues/611#issuecomment-700273405 )
- make saveToPhotoAlbum future proof by using the MediaStore to insert the taken image
- made a method to calculate the compressFormat based on the encodingType (JPEG or PNG)
- layout of the performCrop method is adjusted
- removed unused rotate variable inside processResultFromGallery method

* Add extra VO class to the plugin.xml

* added package declaration to new VO

* GH-341 - GH-577 https://github.com/apache/cordova-plugin-camera/pull/669#discussion_r504632953 listen to review
2020-10-16 23:48:22 -03:00
Norman Breau
43d6591d9e Revert "fix(android): Declare CAMERA permission" (#677)
This reverts commit 140e8861e3.
2020-10-14 21:51:20 -03:00
jcesarmobile
64d8c5108a chore: Fix JIRA links in RELEASENOTES.md (#672) 2020-10-07 15:48:47 +02:00
Norman Breau
11769962bd Merge pull request #670 from breautek/fix/camera-perms
fix(android): Declare CAMERA permission
2020-10-01 07:56:42 -03:00
Norman Breau
140e8861e3 fix(android): Declare CAMERA permission 2020-09-30 22:07:19 -03:00
jcesarmobile
5ae56cf8f0 chore: Update RELEASENOTES (#664) 2020-09-24 17:00:05 +02:00
Erisu
e2e04ba3d8 Increment package version to 5.0.1-dev 2020-09-18 12:06:07 +09:00
Erisu
4584f15d9f Updated version and RELEASENOTES.md for release 5.0.0 (camera-20200914) 2020-09-14 12:19:36 +09:00
エリス
0111e93448 ci(travis): update osx xcode image (#648)
* ci(travis): update osx xcode image
* ci: use travis's latest supported osx_image xcode11.6
2020-09-03 19:35:43 +09:00
jcesarmobile
0333d001c7 breaking: remove NATIVE_URI DestinationType (#637) 2020-08-07 14:38:05 +02:00
エリス
45496213b3 breaking: bump project requirements (#628) 2020-07-28 20:25:48 +09:00
エリス
3f42591363 chore: remove deprecated file transfer plugin (#634) 2020-07-23 20:16:36 +09:00
jcesarmobile
e2ecd7fe91 fix(android): return error if file url is null (#632) 2020-07-23 12:11:55 +02:00
Loïc Le Malliaud
eb7fc333ee fix(android): use provider prefix to avoid conflicts other plugin providers (#510)
Co-authored-by: jcesarmobile <jcesarmobile@gmail.com>
2020-07-16 13:08:40 +02:00
jcesarmobile
fd155d9705 breaking(android): stop using CordovaUri helper class (#617) 2020-07-14 16:26:09 +02:00
エリス
2bf5b9347e chore: add package-lock.json (#630) 2020-07-14 19:26:24 +09:00
エリス
efb633969e chore(package): use short notation (#631) 2020-07-14 19:15:57 +09:00
エリス
973bbbbac7 feat: migrate to @cordova/eslint-config@3.x (#629) 2020-07-14 19:15:29 +09:00
エリス
358522c0b5 ci: fix additional tests (#626) 2020-07-14 17:55:23 +09:00
エリス
8766956abb breaking: bump version 5.0.0-dev (#627) 2020-07-14 17:55:04 +09:00
jcesarmobile
d89c25cd82 fix(ios): tempFilePath called twice if using CameraUsesGeolocation (#612) 2020-06-25 18:23:01 +02:00
Jesse MacFadyen
ba4f77468f chore(release): 4.2.0-dev 2020-05-07 01:34:03 -07:00
Jesse MacFadyen
adf15799d9 Updated version and RELEASENOTES.md for release (Camera-4.2.0) 2020-05-07 00:45:53 -07:00
Jesse MacFadyen
e9aba07926 Merge pull request #588 from purplecabbage/AndroidCacheLocal
[Android] Cache images in device storage, devices have enough space now.
2020-04-30 10:46:21 -07:00
Jesse MacFadyen
df14414203 Cache images in device storage, devices have enough space now. 2020-04-28 13:57:00 -07:00
Norman Breau
2a750f0fa1 Merge pull request #508 from rtpHarry/patch-1
docs(readme): app renamed to Google Photos
2020-04-24 23:09:49 -03:00
Erisu
06ac9b3dc9 chore(asf): update git notification settings 2020-04-22 13:39:50 +09:00
jcesarmobile
bfa38fed2c fix(ios): return copy of video when picking from gallery on iOS 13 (#580) 2020-04-15 11:41:21 +02:00
Niklas Merz
7611960ef2 Update CONTRIBUTING.md 2020-04-13 14:27:10 +02:00
exxbrain
f4067e22d9 Fix UI API called on a background thread (#550, #530, #447) (#551)
Co-authored-by: Denis Zakharov <d.zakharov@bssys.com>
2020-04-09 13:54:26 +00:00
Tim Brust
f33ade83e4 ci: updates Node.js versions (#576) 2020-03-28 12:11:08 +00:00
Tim Brust
6f25420ce7 chore(npm): adds ignore list (#575) 2020-03-28 12:10:44 +00:00
jcesarmobile
6feaa95559 docs(README): remove confusing comment (#513) 2019-10-20 01:05:19 +02:00
jcesarmobile
c887c229f0 docs(README): remove orphan windows phone 7 note (#512) 2019-10-19 17:07:21 +02:00
Matthew Harris
6900fbaefa docs(readme): app renamed to Google Photos 2019-09-25 22:04:31 +07:00
klodha
a9436b1a18 ImagePicker returning same image (#306)
ImagePicker returning same image

Co-authored-by: Jan Piotrowski <piotrowski+github@gmail.com>
Co-authored-by: Tim Brust <github@timbrust.de>
2019-09-16 11:40:54 +02:00
Jan Piotrowski
db4b4b947d chore(release): 4.1.1-dev 2019-06-27 21:04:04 +02:00
Jan Piotrowski
ae3531acfa chore(release): 4.1.0 (version string) 2019-06-27 21:01:58 +02:00
Jan Piotrowski
5b4d9ba5c7 chore(release): release notes for 4.1.0 2019-06-27 21:01:58 +02:00
Jan Piotrowski
06dc38f9ab docs: remove outdated test docs translations 2019-06-27 18:46:33 +02:00
Jan Piotrowski
5dc952724f build: remove .ratignore file that is not needed any more 2019-06-27 18:46:13 +02:00
Jan Piotrowski
cad8bd1442 chore: fix repo and issue urls and license in package.json and plugin.xml 2019-06-27 18:45:52 +02:00
Jan Piotrowski
19d8e2f6ff fix: temporarily remove Appium tests (#468) 2019-06-20 13:30:25 +02:00
Jan Piotrowski
cffd0ac825 ci(travis): Update Travis CI configuration for new paramedic (#455)
* Update .travis.yml

* ADDITIONAL_TESTS

* npm install github:apache/cordova-paramedic\#plugin-test-fixes

* undo

* fix

* ADDITIONAL_TESTS_DIR

* Update .travis.yml

* update to npm 8 for `npm install appium`
2019-06-20 13:25:28 +02:00
Hazem Saleh
295e928784 (Android) Fix NullPointerException error on some Android phones (#429) 2019-05-05 19:16:20 +02:00
Gedas Gardauskas
fae190ead2 Update CI Environment Setup for Node.js 6 (#438) 2019-04-08 23:14:38 +09:00
Hazem Saleh
a13665d530 AAR-232: (android) Enhancement: Camera plugin code cleanup (#425) 2019-03-01 14:00:39 -05:00
Álvaro Herrero
81b878da59 GH-329: (android) Fixes issue: Exif data lost on many cases (#331)
* GH-329 android: Fix Exif data lost when correctOrientation is true

* Changed variable name
2019-02-21 16:51:54 +01:00
Jan Piotrowski
b261d3174f Add or update GitHub pull request and issue template 2019-02-11 18:38:15 +01:00
pz
24c8b6c43d GH-376 (ios) fixes UIImagePickerController cancel handling for iOS11+ (#377) 2018-12-16 12:20:01 +01:00
jcesarmobile
7ddb3dfbbe Remove deprecated platforms from docs (#394) 2018-12-10 00:52:39 +01:00
jcesarmobile
60e779559e Android: return DATA_URL for ALLMEDIA if it's an image (#382) 2018-12-09 12:39:06 +01:00
jcesarmobile
ce77aab010 CB-13813: (iOS) Remove old iOS code (#381) 2018-12-04 12:21:39 +01:00
Ams
cd72047dfc CB-13865: (IOS-Ipad) Making popover Window Size configurable using popoverOptions - imagePicker (#314) 2018-11-25 13:59:51 +01:00
Jan Piotrowski
bfbe4a1e52 fix quirk 2018-11-23 20:18:31 +01:00
jcesarmobile
86b0bf2534 CB-13837: fix TypeScript Definition for CameraPopoverOptions (#379) 2018-11-23 18:44:46 +01:00
Jan Piotrowski
a5a3d88152 clarify android quirk of cameraDirection 2018-11-20 23:40:08 +01:00
jcesarmobile
eed44330a4 Bump minor version (#370) 2018-11-13 23:02:58 +01:00
jcesarmobile
07e85742aa Remove automatic README generation (#365) 2018-11-01 16:13:52 +01:00
jcesarmobile
c0d78ad644 Revert "Bump minor version to 4.1.0-dev (#357)" (#363)
This reverts commit 7ee91a927d.
2018-10-30 16:44:58 +01:00
jcesarmobile
7ee91a927d Bump minor version to 4.1.0-dev (#357) 2018-10-24 13:26:07 +02:00
Jan Piotrowski
bcb26fbbd2 remove JIRA link 2018-10-04 01:15:01 +02:00
Chris Brody
dc73954108 Merge pull request #242 from DisruptiveMind/master
CB-11714: (windows) added check for encoding in savePhoto() without height/width
2018-10-03 18:42:51 -04:00
Jan Piotrowski
c1b9772dca replace double quotes with single quotes 2018-10-03 20:54:06 +02:00
Jan Piotrowski
a346212e90 also accept terms for android sdk android-27 2018-10-01 12:36:47 +02:00
Tyler Pham
eb57b02ba8 CB-11714: reuse picture.name instead of pictureName 2018-09-16 19:22:16 -04:00
Tyler Pham
dca4b9c82b simplify picture.copyAsync 2018-09-16 19:19:13 -04:00
Jan Piotrowski
403682b9d4 remove outdated docs translations that haven't been touched for 3 years 2018-08-18 22:57:23 +02:00
bvmensvoort
5c23b65af9 CB-14097: (android) Fix crash when selecting some files with getPicture (#322)
* CB-14097: (android) Fix crash when selecting some files with getPicture of urls with raw://

Handles both urls:
content://com.android.providers.downloads.documents/document/1111
content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ffilename.pdf

* Optimization: Remove TextUtils dependency, return null when no id could be extracted
2018-07-06 00:16:25 +02:00
jcesarmobile
6899c5ece9 Update engines to use variables (#323) 2018-06-10 23:14:08 +02:00
Matthew Vander Vliet
5163d38465 CB-13384: (browser) Added deprecation of video.src compatibility (#288)
* CB-13384: (browser) Added deprecation of video.src compatibility

* CB-13384: Updated to reflect property detection rather than deprecation exception.
2018-05-25 12:44:23 +08:00
Andrew Decker
36343a8e07 Update CameraProxy.js (#284)
Remove audio flag from getUserMedia on the browser.  Including audio resulted in some nasty audio feedback, and audio isn't really needed for taking pictures anyway.
2018-05-24 13:42:39 +08:00
Nicco Kunzmann
ead7d5e6c2 replace warning emoji with warning unicode (#317)
Due to the use of the emoji, the documentation page shows
⚠️ instead of ⚠.
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html
2018-05-19 12:04:58 +02:00
jcesarmobile
e334656933 CB-14017 (android): Make com.android.support:support-v4 version configurable (#318) 2018-05-19 01:59:48 -04:00
Hazem Saleh
5ec121bf98 CB-14047: (android) CameraLauncher: Replacing Repeated String literals with final variables (#319) 2018-04-22 14:33:52 -04:00
Steve Gill
d9d80e40c1 Set VERSION to 4.0.4-dev (via coho) 2018-04-12 18:06:58 -07:00
Steve Gill
6ce1443622 fixed issue with version, 4.0.3 2018-04-12 18:04:49 -07:00
Steve Gill
37e12e85fb Set VERSION to 4.0.4-dev (via coho) 2018-04-12 17:16:12 -07:00
Steve Gill
9d05a1e58f CB-14030 Updated version and RELEASENOTES.md for release 4.0.3 (via coho) 2018-04-12 17:06:17 -07:00
Joe Bowser
c8581ba2c9 Merge pull request #275 from cjpearson/CB12953
CB-12593: (android) Fix potential FileProvider conflicts
2018-03-14 12:44:35 -07:00
jcesarmobile
e36482c7ba Fix a mistake in the examples of usage descriptions (#313) 2018-02-12 10:36:58 +01:00
Julio César
7c90555bd4 CB-13854(ios): fix Camera opens in portrait orientation on iphones 2018-02-11 21:44:56 -05:00
Tsuruda
e25aed97c5 modified init value (#264) 2018-02-11 18:22:34 +01:00
Alpesh Patel
bf935dfbd2 CB-13415 (android) Importing corrupt images using the Camera plugin c… (#309)
* CB-13415 (android) Importing corrupt images using the Camera plugin crashes the app
2018-02-08 13:12:16 +01:00
Suraj Pindoria
ad8788a5e6 CB-13826 Incremented plugin version. 2018-01-25 11:47:20 -08:00
Suraj Pindoria
4b276ee534 CB-13826 Updated version and RELEASENOTES.md for release 4.0.2 2018-01-25 11:40:16 -08:00
Joe Bowser
4b99623eda Merge pull request #308 from okode/android8_permission_request_fix
CB-13781: (android) Fixed permissions request on Android 8 to save a …
2018-01-15 14:13:07 -08:00
rpanadero
36ea63a60f CB-13781: (android) Fixed permissions request on Android 8 to save a photo into the photo album 2018-01-15 13:05:10 +01:00
jcesarmobile
e6a4738031 Merge pull request #307 from jcesarmobile/CB-13747
CB-13747: Add build-tools-26.0.2 to travis
2018-01-10 23:46:04 +01:00
Julio César
c46fe3b31d CB-13747: Add build-tools-26.0.2 to travis 2018-01-09 20:32:55 +01:00
jcesarmobile
67718544a8 Fix release notes (#304) 2017-12-30 00:59:38 -05:00
Simon MacDonald
b00cf97a04 Set VERSION to 4.0.2-dev (via coho) 2017-12-27 19:13:49 -05:00
Simon MacDonald
fb02f48745 CB-13714 Updated version and RELEASENOTES.md for release 4.0.1 (via coho) 2017-12-27 19:13:36 -05:00
jcesarmobile
6bf45f005a Merge pull request #303 from jcesarmobile/CB-13701
CB-13701 Fix to allow 4.0.0 version install
2017-12-27 10:55:32 +01:00
Julio César
96b7f55ec2 CB-13701Fix to allow 4.0.0 version install 2017-12-27 00:00:45 +01:00
Steve Gill
82f1c83a76 Set VERSION to 4.0.1-dev (via coho) 2017-12-15 17:26:41 -08:00
Steve Gill
4ae0de1c5e CB-13681 Updated version and RELEASENOTES.md for release 4.0.0 (via coho) 2017-12-15 17:25:06 -08:00
Steve Gill
b79c659c92 Merge pull request #301 from surajpindoria/removePlatforms
CB-13661: Remove deprecated platforms
2017-12-13 17:35:44 -08:00
Suraj Pindoria
7fad5d5786 CB-13661: Remove deprecated platforms 2017-12-12 11:09:29 -08:00
Steve Gill
1f86358156 Set VERSION to 3.0.1-dev (via coho) 2017-11-06 14:38:37 -08:00
Steve Gill
d456eeb711 CB-13542 Updated version and RELEASENOTES.md for release 3.0.0 (via coho) 2017-11-06 14:37:41 -08:00
Steve Gill
f761934814 Merge pull request #290 from JoseExposito/master
CB-13421: (osx) Added macOS support
2017-11-03 22:21:09 -07:00
Steve Gill
43b3a911c2 Merge pull request #297 from jcesarmobile/CB-13515
CB-13515 (all): Add 'protective' entry to cordovaDependencies
2017-11-01 13:39:41 -07:00
Julio César
8f033f53db CB-13515 (all): Add 'protective' entry to cordovaDependencies 2017-11-01 12:04:34 +01:00
Julio César
51d665a7a1 CB-13332 (iOS): document NSPhotoLibraryAddUsageDescription
This closes #296
2017-10-21 17:27:52 +02:00
Julio César
9f480b10cb CB-13264 (iOS): Remove ios usage descriptions
This closes #295
2017-10-21 16:45:13 +02:00
Alexander Sorokin
a6706aef5f CB-13473: (CI) Removed browser builds from AppVeyor 2017-10-20 10:11:26 +03:00
Alexander Sorokin
fb213b2b38 CB-13472: (CI) Fixed Travis Android builds again 2017-10-20 08:58:12 +03:00
Julio César
3e24b15934 CB-13446: Sync template with previous doc changes
This closes #291
2017-10-19 18:38:08 -07:00
Kelvin Dart
2acda2d2f9 CB-13294 Remove cordova-plugin-compat
This closes #293
2017-10-19 18:28:14 -07:00
José Expósito
97d2014d62 Adds macOS support 2017-10-10 17:11:10 +02:00
Alexander Sorokin
b2107e0818 CB-13299 (CI) Fix Android builds 2017-09-19 08:58:14 +03:00
Audrey So
16c4325fef CB-12895 : updated src files to use eslint format 2017-07-31 13:29:36 -07:00
Audrey So
80342b0ddd CB-12985 : setup eslint and removed jshint 2017-07-31 11:28:15 -07:00
Alexander Sorokin
55d419a36e CB-13028 (CI) Browser builds on Travis and AppVeyor 2017-07-25 14:50:55 +03:00
Alexander Sorokin
5574490bc3 CB-13002: (Android, iOS) Fix occasional Appium tests failures 2017-07-10 14:51:10 +03:00
Alexander Sorokin
f1b0ccec56 CB-13000: (CI) Speed up android builds 2017-07-10 10:02:24 +03:00
Alexander Sorokin
e69240f251 CB-12991: (CI) Updated CI badges 2017-07-06 13:58:47 +03:00
Alexander Sorokin
5b3a99a6db CB-12990 (iOS) Optimized Appium tests 2017-07-06 12:04:19 +03:00
José Luis Ballesteros del Val
3b8f64e330 CB-12964: (android) Fix of bug when Pictures folder did not exist.
If someone had removed Pictures folder in android, plugin failed trying to move there the new photo. This happened because plugin did not check the existence of this folder, and if not, it did not complete the folder tree.

This closes #273
2017-07-04 14:03:10 +03:00
Alexander Sorokin
f667ba6179 CB-12982: (Android, iOS) Appium tests: try to create a session harder 2017-07-03 18:01:34 +03:00
Connor Pearson
cfefa53272 CB-12593: (android) Fix potential FileProvider conflicts 2017-06-30 10:15:43 -04:00
Alexander Sorokin
77539558e6 CB-12935: (windows) Enable paramedic builds on AppVeyor 2017-06-30 09:30:25 +03:00
Alexander Sorokin
cba99940a7 CB-12935: (android, ios) Run paramedic tests on Travis 2017-06-23 09:56:20 +03:00
Jacques de Villiers
7155b636d5 Incorrect "JIRA issue tracker" link in Readme 2017-06-19 14:37:15 +01:00
Shazron Abdullah
160ed2d03f CB-12912 - Incorrect 'Report Bugs' link in README
This closes #270
2017-06-14 01:59:09 -07:00
Sergii Stotskyi
c3d7e55ad4 CB-12682: (ios, android): changes cancel error message to be consistent for ios android 2017-06-07 07:36:30 +03:00
Alexander Sorokin
1b218cd8a0 CB-12764: (android) Adapt Appium tests for Android 7 2017-06-02 15:02:10 +03:00
filmaj
51e5c02dcb CB-12847: fixed bugs entry in package.json. 2017-05-25 12:35:40 +02:00
filmaj
26d13b0245 CB-12847: added bugs entry to package.json. 2017-05-24 21:11:53 +02:00
filmaj
ef617cc943 Close #265 2017-05-10 09:15:40 -07:00
filmaj
1422b0a4f2 Set VERSION to 2.4.2-dev (via coho) 2017-04-27 10:27:41 -07:00
Tyler Pham
a201722f6d CB-11714: (windows) added extra check for content-type in savePhoto() without options.targetWidth/Height 2016-12-01 14:12:01 -05:00
106 changed files with 7201 additions and 13679 deletions

46
.asf.yaml Normal file
View File

@@ -0,0 +1,46 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
github:
description: Apache Cordova Plugin camera
homepage: https://cordova.apache.org/
labels:
- cordova
- mobile
- javascript
- nodejs
- hacktoberfest
- java
- objective-c
- cordova-plugin
features:
wiki: false
issues: true
projects: true
enabled_merge_buttons:
squash: true
merge: false
rebase: false
notifications:
commits: commits@cordova.apache.org
issues: issues@cordova.apache.org
pullrequests_status: issues@cordova.apache.org
pullrequests_comment: issues@cordova.apache.org

23
.eslintrc.yml Normal file
View File

@@ -0,0 +1,23 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
root: true
extends: '@cordova/eslint-config/browser'
overrides:
- files: [tests/**/*.js]
extends: '@cordova/eslint-config/node-tests'

42
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,42 @@
<!--
Please have a look at the issue templates you get when you click "New issue" in the GitHub UI.
We very much prefer issues created by using one of these templates.
-->
### Issue Type
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] Bug Report
- [ ] Feature Request
- [ ] Support Question
## Description
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an `x` in the `[ ]` like so: `[x]` -->
- [ ] I searched for already existing GitHub issues about this
- [ ] I updated all Cordova tooling to their most recent version
- [ ] I included all the necessary information above

50
.github/ISSUE_TEMPLATE/BUG_REPORT.md vendored Normal file
View File

@@ -0,0 +1,50 @@
---
name: 🐛 Bug Report
about: If something isn't working as expected.
---
# Bug Report
## Problem
### What is expected to happen?
### What does actually happen?
## Information
<!-- Include all relevant information that might help understand and reproduce the problem -->
### Command or Code
<!-- What command or code is needed to reproduce the problem? -->
### Environment, Platform, Device
<!-- In what environment, on what platform or on which device are you experiencing the issue? -->
### Version information
<!--
What are relevant versions you are using?
For example:
Cordova: Cordova CLI, Cordova Platforms, Cordova Plugins
Other Frameworks: Ionic Framework and CLI version
Operating System, Android Studio, Xcode etc.
-->
## Checklist
<!-- Please check the boxes by putting an x in the [ ] like so: [x] -->
- [ ] I searched for existing GitHub issues
- [ ] I updated all Cordova tooling to most recent version
- [ ] I included all the necessary information above

View File

@@ -0,0 +1,29 @@
---
name: 🚀 Feature Request
about: A suggestion for a new functionality
---
# Feature Request
## Motivation Behind Feature
<!-- Why should this feature be implemented? What problem does it solve? -->
## Feature Description
<!--
Describe your feature request in detail
Please provide any code examples or screenshots of what this feature would look like
Are there any drawbacks? Will this break anything for existing users?
-->
## Alternatives or Workarounds
<!--
Describe alternatives or workarounds you are currently using
Are there ways to do this with existing functionality?
-->

View File

@@ -0,0 +1,26 @@
---
name: 💬 Support Question
about: If you have a question, please check out our Slack or StackOverflow!
---
<!------------^ Click "Preview" for a nicer view! -->
Apache Cordova uses GitHub Issues as a feature request and bug tracker _only_.
For usage and support questions, please check out the resources below. Thanks!
---
You can get answers to your usage and support questions about **Apache Cordova** on:
* GitHub Discussions: https://github.com/apache/cordova/discussions
* Slack Community Chat: https://cordova.slack.com (you can sign-up at https://s.apache.org/cordova-slack)
* StackOverflow: https://stackoverflow.com/questions/tagged/cordova using the tag `cordova`
---
If you are using a tool that uses Cordova internally, like e.g. Ionic, check their support channels:
* **Ionic Framework**
* [Ionic Community Forum](https://forum.ionicframework.com/)
* [Ionic Discord](https://ionic.link/discord)

View File

@@ -1,6 +1,5 @@
<!--
Please make sure the checklist boxes are all checked before submitting the PR. The checklist
is intended as a quick reference, for complete details please see our Contributor Guidelines:
Please make sure the checklist boxes are all checked before submitting the PR. The checklist is intended as a quick reference, for complete details please see our Contributor Guidelines:
http://cordova.apache.org/contribute/contribute_guidelines.html
@@ -10,13 +9,27 @@ Thanks!
### Platforms affected
### What does this PR do?
### Motivation and Context
<!-- Why is this change required? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here. -->
### What testing has been done on this change?
### Description
<!-- Describe your changes in detail -->
### Testing
<!-- Please describe in detail how you tested your changes. -->
### Checklist
- [ ] [Reported an issue](http://cordova.apache.org/contribute/issues.html) in the JIRA database
- [ ] Commit message follows the format: "CB-3232: (android) Fix bug with resolving file paths", where CB-xxxx is the JIRA ID & "android" is the platform affected.
- [ ] Added automated test coverage as appropriate for this change.
- [ ] I've run the tests to see all new and existing tests pass
- [ ] I added automated test coverage as appropriate for this change
- [ ] Commit is prefixed with `(platform)` if this change only applies to one platform (e.g. `(android)`)
- [ ] If this Pull Request resolves an issue, I linked to the issue in the text above (and used the correct [keyword to close issues using keywords](https://help.github.com/articles/closing-issues-using-keywords/))
- [ ] I've updated the documentation if necessary

161
.github/workflows/android.yml vendored Normal file
View File

@@ -0,0 +1,161 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: Android Testsuite
on:
push:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
pull_request:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
jobs:
test:
name: Android ${{ matrix.versions.android }} Test
runs-on: ubuntu-latest
continue-on-error: true
# hoist configurations to top that are expected to be updated
env:
# Storing a copy of the repo
repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
node-version: 20
# These are the default Java configurations used by most tests.
# To customize these options, add "java-distro" or "java-version" to the strategy matrix with its overriding value.
default_java-distro: temurin
default_java-version: 17
# These are the default Android System Image configurations used by most tests.
# To customize these options, add "system-image-arch" or "system-image-target" to the strategy matrix with its overriding value.
default_system-image-arch: x86_64
default_system-image-target: google_apis # Most system images have a google_api option. Set this as default.
# configurations for each testing strategy (test matrix)
strategy:
matrix:
versions:
- android: 7
android-api: 24
- android: 7.1
android-api: 25
- android: 8
android-api: 26
- android: 8.1
android-api: 27
system-image-arch: x86
- android: 9
android-api: 28
- android: 10
android-api: 29
- android: 11
android-api: 30
- android: 12
android-api: 31
- android: 12L
android-api: 32
- android: 13
android-api: 33
- android: 14
android-api: 34
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.node-version }}
- uses: actions/setup-java@v4
env:
java-version: ${{ matrix.versions.java-version == '' && env.default_java-version || matrix.versions.java-version }}
java-distro: ${{ matrix.versions.java-distro == '' && env.default_java-distro || matrix.versions.java-distro }}
with:
distribution: ${{ env.java-distro }}
java-version: ${{ env.java-version }}
- name: Enable KVM group perms
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
sudo udevadm control --reload-rules
sudo udevadm trigger --name-match=kvm
- name: Run Environment Information
run: |
node --version
npm --version
java -version
- name: Run npm install
run: |
export PATH="/usr/local/lib/android/sdk/platform-tools":$PATH
export JAVA_HOME=$JAVA_HOME_11_X64
npm i -g cordova@latest
npm ci
- name: Run paramedic install
if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
run: npm i -g github:apache/cordova-paramedic
- uses: reactivecircus/android-emulator-runner@v2
env:
system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }}
system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }}
with:
api-level: ${{ matrix.versions.android-api }}
target: ${{ env.system-image-target }}
arch: ${{ env.system-image-arch }}
force-avd-creation: false
disable-animations: false
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim
script: echo "Pregenerate the AVD before running Paramedic"
- name: Run paramedic tests
uses: reactivecircus/android-emulator-runner@v2
env:
system-image-arch: ${{ matrix.versions.system-image-arch == '' && env.default_system-image-arch || matrix.versions.system-image-arch }}
system-image-target: ${{ matrix.versions.system-image-target == '' && env.default_system-image-target || matrix.versions.system-image-target }}
test_config: 'android-${{ matrix.versions.android }}.config.json'
# Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
with:
api-level: ${{ matrix.versions.android-api }}
target: ${{ env.system-image-target }}
arch: ${{ env.system-image-arch }}
force-avd-creation: false
disable-animations: false
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim
script: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}

73
.github/workflows/chrome.yml vendored Normal file
View File

@@ -0,0 +1,73 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: Chrome Testsuite
on:
push:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
pull_request:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
jobs:
test:
name: Chrome Latest Test
runs-on: ubuntu-latest
# hoist configurations to top that are expected to be updated
env:
# Storing a copy of the repo
repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
node-version: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.node-version }}
- name: Run install xvfb
run: sudo apt-get install xvfb
- name: Run Environment Information
run: |
node --version
npm --version
- name: Run npm install
run: |
npm i -g cordova@latest
npm ci
- name: Run paramedic install
if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
run: npm i -g github:apache/cordova-paramedic
- name: Run paramedic tests
env:
test_config: 'browser.config.json'
# Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
run: xvfb-run --auto-servernum ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}

105
.github/workflows/ios.yml vendored Normal file
View File

@@ -0,0 +1,105 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: iOS Testsuite
on:
push:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
pull_request:
paths-ignore:
- '**.md'
- 'LICENSE'
- '.eslint*'
jobs:
test:
name: iOS ${{ matrix.versions.ios-version }} Test
runs-on: ${{ matrix.versions.os-version }}
continue-on-error: true
# hoist configurations to top that are expected to be updated
env:
# Storing a copy of the repo
repo: ${{ github.event.pull_request.head.repo.full_name || github.repository }}
node-version: 20
# > Starting April 26, 2021, all iOS and iPadOS apps submitted to the App Store must be built with Xcode 12 and the iOS 14 SDK.
# Because of Apple's requirement, listed above, We will only be using the latest Xcode release for testing.
# To customize these options, add "xcode-version" to the strategy matrix with its overriding value.
default_xcode-version: latest-stable
strategy:
matrix:
versions:
- os-version: macos-14
ios-version: 15.x
xcode-version: 15.x
- os-version: macos-14
ios-version: 16.x
xcode-version: 15.x
- os-version: macos-14
ios-version: 17.x
xcode-version: 15.x
- os-version: macos-15
ios-version: 18.x
xcode-version: 16.x
- os-version: macos-26
ios-version: 26.x
xcode-version: 26.x
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.node-version }}
- uses: maxim-lobanov/setup-xcode@60606e260d2fc5762a71e64e74b2174e8ea3c8bd
env:
xcode-version: ${{ matrix.versions.xcode-version == '' && env.default_xcode-version || matrix.versions.xcode-version }}
with:
xcode-version: ${{ env.xcode-version }}
- name: Run Environment Information
run: |
node --version
npm --version
xcodebuild -version
- name: Run npm install
run: |
npm i -g cordova@latest ios-deploy@latest
npm ci
- name: Run paramedic install
if: ${{ endswith(env.repo, '/cordova-paramedic') != true }}
run: npm i -g github:apache/cordova-paramedic
- name: Run paramedic tests
env:
test_config: 'ios-${{ matrix.versions.ios-version }}.config.json'
# Generally, this should automatically work for cordova-paramedic & plugins. If the path is unique, this can be manually changed.
test_plugin_path: ${{ endswith(env.repo, '/cordova-paramedic') && './spec/testable-plugin/' || './' }}
paramedic: ${{ endswith(env.repo, '/cordova-paramedic') && 'node main.js' || 'cordova-paramedic' }}
run: ${{ env.paramedic }} --config ./pr/local/${{ env.test_config }} --plugin ${{ env.test_plugin_path }}

56
.github/workflows/lint.yml vendored Normal file
View File

@@ -0,0 +1,56 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: Lint Test
on:
push:
paths:
- '**.js'
- '.eslint*'
- '.github/workflow/lint.yml'
pull_request:
paths:
- '**.js'
- '.eslint*'
- '.github/workflow/lint.yml'
jobs:
test:
name: Lint Test
runs-on: ubuntu-latest
env:
node-version: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.node-version }}
- name: Run Environment Information
run: |
node --version
npm --version
- name: Run npm install
run: |
npm ci
- name: Run lint test
run: |
npm run lint

13
.github/workflows/release-notify.yml vendored Normal file
View File

@@ -0,0 +1,13 @@
name: Close issue asking for release
on:
issues:
types: [opened]
jobs:
action-test:
runs-on: ubuntu-latest
steps:
- uses: niklasmerz/release-notify@master
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,16 +0,0 @@
{
"browser": true
, "devel": true
, "bitwise": true
, "undef": true
, "trailing": true
, "quotmark": false
, "indent": 4
, "unused": "vars"
, "latedef": "nofunc"
, "globals": {
"module": false,
"exports": false,
"require": false
}
}

2
.npmignore Normal file
View File

@@ -0,0 +1,2 @@
.*
tests

2
.npmrc Normal file
View File

@@ -0,0 +1,2 @@
registry=https://registry.npmjs.org

View File

@@ -1 +0,0 @@
TEMPLATE.md

View File

@@ -1,8 +0,0 @@
language: objective-c
sudo: false
node_js:
- "4.2"
env:
- TEST_DIR=.
- TEST_DIR=./tests/ios
script: cd $TEST_DIR && npm install && npm test

View File

@@ -25,13 +25,13 @@ Anyone can contribute to Cordova. And we need your contributions.
There are multiple ways to contribute: report bugs, improve the docs, and
contribute code.
For instructions on this, start with the
For instructions on this, start with the
[contribution overview](http://cordova.apache.org/contribute/).
The details are explained there, but the important items are:
- Sign and submit an Apache ICLA (Contributor License Agreement).
- Have a Jira issue open that corresponds to your contribution.
- Check for Github issues that corresponds to your contribution and link or create them if necessary.
- Run the tests so your patch doesn't break existing functionality.
We look forward to your contributions!

559
README.md
View File

@@ -21,78 +21,84 @@ description: Take pictures with the device camera.
# under the License.
-->
|Android 4.4|Android 5.1|Android 6.0|iOS 9.3|iOS 10.0|Windows 10 Store|Travis CI|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|[![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)
# cordova-plugin-camera
[![Android Testsuite](https://github.com/apache/cordova-plugin-camera/actions/workflows/android.yml/badge.svg)](https://github.com/apache/cordova-plugin-camera/actions/workflows/android.yml) [![Chrome Testsuite](https://github.com/apache/cordova-plugin-camera/actions/workflows/chrome.yml/badge.svg)](https://github.com/apache/cordova-plugin-camera/actions/workflows/chrome.yml) [![iOS Testsuite](https://github.com/apache/cordova-plugin-camera/actions/workflows/ios.yml/badge.svg)](https://github.com/apache/cordova-plugin-camera/actions/workflows/ios.yml) [![Lint Test](https://github.com/apache/cordova-plugin-camera/actions/workflows/lint.yml/badge.svg)](https://github.com/apache/cordova-plugin-camera/actions/workflows/lint.yml)
This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from
the system's image library.
Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
```js
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
```
## Installation
This requires cordova 5.0+
cordova plugin add cordova-plugin-camera
Older versions of cordova can still install via the __deprecated__ id
cordova plugin add org.apache.cordova.camera
It is also possible to install via repo url directly ( unstable )
cordova plugin add https://github.com/apache/cordova-plugin-camera.git
## Plugin variables
The plugin uses the `ANDROIDX_CORE_VERSION` variable to configure `androidx.core:core` dependency. This allows to avoid conflicts with other plugins that have the dependency hardcoded.
If no value is passed, it will use `1.6.+` as the default value.
The variable is configured on install time
cordova plugin add cordova-plugin-camera --variable ANDROIDX_CORE_VERSION=1.8.0
## How to Contribute
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).
Contributors 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).
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).
: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).
**Have a solution?** Send a [Pull Request](https://github.com/apache/cordova-plugin-camera/pulls).
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).
**And don't forget to test and document your code.**
### iOS Specifics
## This documentation is generated by a tool
Since iOS 10 it's mandatory to provide a usage description in the `info.plist` when accessing privacy-sensitive data. The required keys depend on how you use the plugin and which iOS versions you support:
:warning: Run `npm install` in the plugin repo to enable automatic docs generation if you plan to send a PR.
[jsdoc-to-markdown](https://www.npmjs.com/package/jsdoc-to-markdown) is used to generate the docs.
Documentation consists of template and API docs produced from the plugin JS code and should be regenerated before each commit (done automatically via [husky](https://github.com/typicode/husky), running `npm run gen-docs` script as a `precommit` hook - see `package.json` for details).
| Key | Description |
| ------------------------------ | ----------- |
| NSCameraUsageDescription | Required whenever the camera is used (e.g. `Camera.PictureSourceType.CAMERA`). |
| NSPhotoLibraryUsageDescription | Required only when your app runs on iOS 13 or older and using as `sourceType` `Camera.PictureSourceType.PHOTOLIBRARY`. On iOS 14+ the plugin uses PHPicker for read-only access, which does not need this key. |
| NSPhotoLibraryAddUsageDescription | Required when the plugin writes to the user's library (e.g. `saveToPhotoAlbum=true`). |
| NSLocationWhenInUseUsageDescription | Required if `CameraUsesGeolocation` is set to `true`. |
When the system prompts the user to allow access, this usage description string will be displayed as part of the permission dialog box. If you don't provide the required usage description, the app will crash before showing the dialog. Also, Apple will reject apps that access private data but don't provide a usage description.
To add these entries into the `info.plist`, you can use the `edit-config` tag in the `config.xml` like this:
### iOS Quirks
```xml
<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
<string>need camera access to take pictures</string>
</edit-config>
Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist.
<edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge">
<string>need photo library access to get pictures from there</string>
</edit-config>
- `NSCameraUsageDescription` describes the reason that the app accesses the users camera.
- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library.
<edit-config target="NSPhotoLibraryAddUsageDescription" file="*-Info.plist" mode="merge">
<string>need photo library access to save pictures there</string>
</edit-config>
When the system prompts the user to allow access, this string is displayed as part of the dialog box.
To add this entry you can pass the following variables on plugin install.
- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription`
- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription`
Example:
cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
If you don't pass the variable, the plugin will add an empty string as value.
<edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
<string>need location access to find things nearby</string>
</edit-config>
```
---
@@ -112,12 +118,8 @@ If you don't pass the variable, the plugin will add an empty string as value.
* [.EncodingType](#module_Camera.EncodingType) : <code>enum</code>
* [.MediaType](#module_Camera.MediaType) : <code>enum</code>
* [.PictureSourceType](#module_Camera.PictureSourceType) : <code>enum</code>
* [.PopoverArrowDirection](#module_Camera.PopoverArrowDirection) : <code>enum</code>
* [.Direction](#module_Camera.Direction) : <code>enum</code>
* [CameraPopoverHandle](#module_CameraPopoverHandle)
* [CameraPopoverOptions](#module_CameraPopoverOptions)
---
<a name="module_camera"></a>
@@ -127,8 +129,31 @@ If you don't pass the variable, the plugin will add an empty string as value.
### camera.getPicture(successCallback, errorCallback, options)
Takes a photo using the camera, or retrieves a photo from the device's
image gallery. The image is passed to the success callback as a
Base64-encoded `String`, or as the URI for the image file.
image gallery. The result is provided in the first parameter of the `successCallback` as a string.
As of v8.0.0, the result is formatted as URIs. The scheme will vary depending on settings and platform.
|Platform|Destination Type|Format|
|---|---|---|
|Android|FILE_URI|An URI scheme such as `file://...` or `content://...`|
||DATA_URL|Base 64 encoded with the proper data URI header|
|iOS|FILE_URI|`file://` schemed paths|
||DATA_URL|Base 64 encoded with the proper data URI header|
|Browser|FILE_URI|Not supported|
||DATA_URL|Base 64 encoded with the proper data URI header|
v7 and earlier versions, the return format is as follows:
|Platform|Destination Type|Format|
|---|---|---|
|Android|FILE_URI|Raw file path (unprefixed)|
||DATA_URL|Base 64 encoded, without the `data:` prefix
|iOS|FILE_URI|`file://` schemed paths|
||DATA_URL|Base 64 encoded, without the `data:` prefix
|Browser|FILE_URI|Not supported|
||DATA_URL|Base 64 encoded, without the `data:` prefix|
For this reason, upgrading to v8 is strongly recommended as it greatly streamlines the return data.
The `camera.getPicture` function opens the device's default camera
application that allows users to snap pictures by default - this behavior occurs,
@@ -141,16 +166,10 @@ that allows users to select an existing image.
The return value is sent to the [`cameraSuccess`](#module_camera.onSuccess) callback function, in
one of the following formats, depending on the specified
`cameraOptions`:
`cameraOptions`. You can do whatever you want with content:
- A `String` containing the Base64-encoded photo image.
- A `String` representing the image file location on local storage (default).
You can do whatever you want with the encoded image or URI, for
example:
- Render the image in an `<img>` tag, as in the example below
- Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
- Render the content in an `<img>` or `<video>` tag
- Copy the data to a persistent location
- Post the data to a remote server
__NOTE__: Photo resolution on newer devices is quite good. Photos
@@ -159,21 +178,41 @@ quality, even if a `quality` parameter is specified. To avoid common
memory problems, set `Camera.destinationType` to `FILE_URI` rather
than `DATA_URL`.
__NOTE__: To use `saveToPhotoAlbum` option on Android 9 (API 28) and lower, the `WRITE_EXTERNAL_STORAGE` permission must be declared.
To do this, add the following in your `config.xml`:
```xml
<config-file target="AndroidManifest.xml" parent="/*" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
</config-file>
```
Android 10 (API 29) and later devices does not require `WRITE_EXTERNAL_STORAGE` permission. If your application only supports Android 10 or later, then this step is not necessary.
#### FILE_URI Usage
When `FILE_URI` is used, the returned path is not directly usable. The file path needs to be resolved into
a DOM-usable URL using the [Cordova File Plugin](https://github.com/apache/cordova-plugin-file).
Additionally, the file URIs returned is a temporary read access grant. The OS reserves the right to revoke permission to access the resource, which typically occurs after the app has been closed. For images captured using the camera, the image is stored in a temporary location which can be cleared at any time, usually after the app exits. It's the application's decision to decide how the content should be used depending on their use cases.
For persistent access to the content, the resource should be copied to your app's storage container. An example use case is an app allowing an user to select a profile picture from their gallery or camera. The application will need
consistent access to that resource, so it's not suitable to retain the temporary access path. So the appplication should copy the resource to a persistent location.
For use cases that involve temporary use, it is valid and safe to use the temporary file path to display the content. An example of this could be an image editing application, rendering the data into a canvas.
__NOTE__: The returned schemes is an implementation detail. Do not assume that it will always be a `file://` URI.
__Supported Platforms__
- Android
- BlackBerry
- Browser
- Firefox
- FireOS
- iOS
- Windows
- WP8
- Ubuntu
More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).
**Kind**: static method of <code>[camera](#module_camera)</code>
**Kind**: static method of <code>[camera](#module_camera)</code>
| Param | Type | Description |
| --- | --- | --- |
@@ -181,7 +220,7 @@ More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPict
| errorCallback | <code>[onError](#module_camera.onError)</code> | |
| options | <code>[CameraOptions](#module_camera.CameraOptions)</code> | CameraOptions |
**Example**
**Example**
```js
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
```
@@ -197,8 +236,8 @@ __Supported Platforms__
- iOS
**Kind**: static method of <code>[camera](#module_camera)</code>
**Example**
**Kind**: static method of <code>[camera](#module_camera)</code>
**Example**
```js
navigator.camera.cleanup(onSuccess, onFail);
@@ -215,7 +254,7 @@ function onFail(message) {
### camera.onError : <code>function</code>
Callback function that provides an error message.
**Kind**: static typedef of <code>[camera](#module_camera)</code>
**Kind**: static typedef of <code>[camera](#module_camera)</code>
| Param | Type | Description |
| --- | --- | --- |
@@ -226,19 +265,26 @@ Callback function that provides an error message.
### camera.onSuccess : <code>function</code>
Callback function that provides the image data.
**Kind**: static typedef of <code>[camera](#module_camera)</code>
**Kind**: static typedef of <code>[camera](#module_camera)</code>
| Param | Type | Description |
| --- | --- | --- |
| imageData | <code>string</code> | Base64 encoding of the image data, _or_ the image file URI, depending on [`cameraOptions`](#module_camera.CameraOptions) in effect. |
| imageData | <code>string</code> | Data URI, _or_ the image file URI, depending on [`cameraOptions`](#module_camera.CameraOptions) in effect. |
**Example**
**Example**
```js
// Show image
//
// Show image captured with FILE_URI
function cameraCallback(imageData) {
window.resolveLocalFileSystemURL(uri, (entry) => {
let image = document.getElementById('myImage');
image.src = entry.toURL();
}, onError);
}
// Show image captured with DATA_URL
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
image.src = imageData;
}
```
<a name="module_camera.CameraOptions"></a>
@@ -247,7 +293,7 @@ function cameraCallback(imageData) {
Optional parameters to customize the camera settings.
* [Quirks](#CameraOptions-quirks)
**Kind**: static typedef of <code>[camera](#module_camera)</code>
**Kind**: static typedef of <code>[camera](#module_camera)</code>
**Properties**
| Name | Type | Default | Description |
@@ -255,14 +301,13 @@ Optional parameters to customize the camera settings.
| 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.) |
| destinationType | <code>[DestinationType](#module_Camera.DestinationType)</code> | <code>FILE_URI</code> | Choose the format of the return value. |
| sourceType | <code>[PictureSourceType](#module_Camera.PictureSourceType)</code> | <code>CAMERA</code> | Set the source of the picture. |
| allowEdit | <code>Boolean</code> | <code>true</code> | Allow simple editing of image before selection. |
| ~~allowEdit~~ | <code>Boolean</code> | <code>false</code> | **Deprecated**. Allow simple editing of image before selection. |
| encodingType | <code>[EncodingType](#module_Camera.EncodingType)</code> | <code>JPEG</code> | Choose the returned image file's encoding. |
| targetWidth | <code>number</code> | | Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant. |
| targetHeight | <code>number</code> | | Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant. |
| 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`. |
| correctOrientation | <code>Boolean</code> | | Rotate the image to correct for the orientation of the device during capture. |
| saveToPhotoAlbum | <code>Boolean</code> | | Save the image to the photo album on the device after capture. |
| popoverOptions | <code>[CameraPopoverOptions](#module_CameraPopoverOptions)</code> | | iOS-only options that specify popover location in iPad. |
| saveToPhotoAlbum | <code>Boolean</code> | | Save the image to the photo album on the device after capture.<br />See [Android Quirks](#cameragetpicturesuccesscallback-errorcallback-options). |
| cameraDirection | <code>[Direction](#module_Camera.Direction)</code> | <code>BACK</code> | Choose the camera to use (front- or back-facing). |
---
@@ -274,24 +319,19 @@ Optional parameters to customize the camera settings.
### Camera.DestinationType : <code>enum</code>
Defines the output format of `Camera.getPicture` call.
_Note:_ On iOS passing `DestinationType.NATIVE_URI` along with
`PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM` will
disable any image modifications (resize, quality change, cropping, etc.) due
to implementation specific.
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| 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 |
| DATA_URL | <code>number</code> | <code>0</code> | Return data uri. DATA_URL can be very memory intensive and cause app crashes or out of memory errors. Use FILE_URI if possible |
| FILE_URI | <code>number</code> | <code>1</code> | Return file uri (content://media/external/images/media/2 for Android) |
| NATIVE_URI | <code>number</code> | <code>2</code> | Return native uri (eg. asset-library://... for iOS) |
<a name="module_Camera.EncodingType"></a>
### Camera.EncodingType : <code>enum</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Properties**
| Name | Type | Default | Description |
@@ -302,7 +342,7 @@ to implementation specific.
<a name="module_Camera.MediaType"></a>
### Camera.MediaType : <code>enum</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Properties**
| Name | Type | Default | Description |
@@ -315,39 +355,20 @@ to implementation specific.
### Camera.PictureSourceType : <code>enum</code>
Defines the output format of `Camera.getPicture` call.
_Note:_ On iOS passing `PictureSourceType.PHOTOLIBRARY` or `PictureSourceType.SAVEDPHOTOALBUM`
along with `DestinationType.NATIVE_URI` will disable any image modifications (resize, quality
change, cropping, etc.) due to implementation specific.
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| PHOTOLIBRARY | <code>number</code> | <code>0</code> | Choose image from the device's photo library (same as SAVEDPHOTOALBUM for Android) |
| PHOTOLIBRARY | <code>number</code> | <code>0</code> | Choose image from the device's photo library. |
| CAMERA | <code>number</code> | <code>1</code> | Take picture from camera |
| SAVEDPHOTOALBUM | <code>number</code> | <code>2</code> | Choose image only from the device's Camera Roll album (same as PHOTOLIBRARY for Android) |
<a name="module_Camera.PopoverArrowDirection"></a>
### Camera.PopoverArrowDirection : <code>enum</code>
Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Properties**
| Name | Type | Default |
| --- | --- | --- |
| ARROW_UP | <code>number</code> | <code>1</code> |
| ARROW_DOWN | <code>number</code> | <code>2</code> |
| ARROW_LEFT | <code>number</code> | <code>4</code> |
| ARROW_RIGHT | <code>number</code> | <code>8</code> |
| ARROW_ANY | <code>number</code> | <code>15</code> |
| SAVEDPHOTOALBUM | <code>number</code> | <code>2</code> | Same as `PHOTOLIBRARY`, when running on Android or iOS 14+. On iOS older than 14, an image can only be chosen from the device's Camera Roll album with this setting. |
<a name="module_Camera.Direction"></a>
### Camera.Direction : <code>enum</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Kind**: static enum property of <code>[Camera](#module_Camera)</code>
**Properties**
| Name | Type | Default | Description |
@@ -357,94 +378,52 @@ Matches iOS UIPopoverArrowDirection constants to specify arrow location on popov
---
<a name="module_CameraPopoverOptions"></a>
## CameraPopoverOptions
iOS-only parameters that specify the anchor element location and arrow
direction of the popover when selecting images from an iPad's library
or album.
Note that the size of the popover may change to adjust to the
direction of the arrow and orientation of the screen. Make sure to
account for orientation changes when specifying the anchor element
location.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [x] | <code>Number</code> | <code>0</code> | x pixel coordinate of screen element onto which to anchor the popover. |
| [y] | <code>Number</code> | <code>32</code> | y pixel coordinate of screen element onto which to anchor the popover. |
| [width] | <code>Number</code> | <code>320</code> | width, in pixels, of the screen element onto which to anchor the popover. |
| [height] | <code>Number</code> | <code>480</code> | height, in pixels, of the screen element onto which to anchor the popover. |
| [arrowDir] | <code>[PopoverArrowDirection](#module_Camera.PopoverArrowDirection)</code> | <code>ARROW_ANY</code> | Direction the arrow on the popover should point. |
---
<a name="module_CameraPopoverHandle"></a>
## CameraPopoverHandle
A handle to an image picker popover.
__Supported Platforms__
- iOS
**Example**
```js
navigator.camera.getPicture(onSuccess, onFail,
{
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverHandle = new CameraPopoverHandle();
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
```
---
## `camera.getPicture` Errata
#### Example <a name="camera-getPicture-examples"></a>
Take a photo and retrieve the image's file location:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
```javascript
// Don't forget to install cordova-plugin-file for resolveLocalFileSystemURL!
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onFail(message) {
alert('Failed because: ' + message);
}
function onSuccess(imageURI) {
window.resolveLocalFileSystemURL(uri, (entry) => {
let img = document.getElementById('image');
img.src = entry.toURL();
}, onFail);
}
function onFail(message) {
alert('Failed because: ' + message);
}
```
Take a photo and retrieve it as a Base64-encoded image:
/**
* Warning: Using DATA_URL is not recommended! The DATA_URL destination
* type is very memory intensive, even with a low quality setting. Using it
* can result in out of memory errors and application crashes. Use FILE_URI
* or NATIVE_URI instead.
*/
navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
destinationType: Camera.DestinationType.DATA_URL
});
```javascript
/**
* Warning: Using DATA_URL is not recommended! The DATA_URL destination
* type is very memory intensive, even with a low quality setting. Using it
* can result in out of memory errors and application crashes. Use FILE_URI
* instead.
*/
navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function onFail(message) {
alert('Failed because: ' + message);
}
```
#### Preferences (iOS)
@@ -452,12 +431,6 @@ Take a photo and retrieve it as a Base64-encoded image:
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon Fire OS Quirks <a name="camera-getPicture-quirks"></a>
Amazon Fire OS uses intents to launch the camera activity on the device to capture
images, and on phones with low memory, the Cordova activity may be killed. In this
scenario, the image may not appear when the Cordova activity is restored.
#### Android Quirks
Android uses intents to launch the camera activity on the device to capture
@@ -471,127 +444,34 @@ successful.
#### Browser Quirks
Can only return photos as Base64-encoded image.
#### Firefox OS Quirks
Camera plugin is currently implemented using [Web Activities][web_activities].
Can only return photos as data URI image.
#### iOS Quirks
Including a JavaScript `alert()` in either of the callback functions
can cause problems. Wrap the alert within a `setTimeout()` to allow
the iOS image picker or popover to fully close before the alert
the iOS image picker to fully close before the alert
displays:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 Quirks
Invoking the native camera application while the device is connected
via Zune does not work, and triggers an error callback.
#### Windows quirks
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
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
start page from scratch and success and error callbacks will never be called.
To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page.
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)
#### Tizen Quirks
Tizen only supports a `destinationType` of
`Camera.DestinationType.FILE_URI` and a `sourceType` of
`Camera.PictureSourceType.PHOTOLIBRARY`.
```javascript
setTimeout(function() {
// do your thing here!
}, 0);
```
## `CameraOptions` Errata <a name="CameraOptions-quirks"></a>
#### Amazon Fire OS Quirks
- Any `cameraDirection` value results in a back-facing photo.
- Ignores the `allowEdit` parameter.
- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
#### Android Quirks
- Any `cameraDirection` value results in a back-facing photo.
- Any `cameraDirection` value results in a back-facing photo. (= You can only use the back camera)
- **`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.
- **`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 Photos), but it is unwise to rely on that being the case. If image editing is essential to your application, consider seeking a third party library or plugin that provides its own image editing utility for a more robust solution.
- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
- Ignores the `encodingType` parameter if the image is unedited (i.e. `quality` is 100, `correctOrientation` is false, and no `targetHeight` or `targetWidth` are specified). The `CAMERA` source will always return the JPEG file given by the native camera and the `PHOTOLIBRARY` and `SAVEDPHOTOALBUM` sources will return the selected file in its existing encoding.
#### BlackBerry 10 Quirks
- Ignores the `quality` parameter.
- Ignores the `allowEdit` parameter.
- `Camera.MediaType` is not supported.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
#### Firefox OS Quirks
- Ignores the `quality` parameter.
- `Camera.DestinationType` is ignored and equals `1` (image file URI)
- Ignores the `allowEdit` parameter.
- Ignores the `PictureSourceType` parameter (user chooses it in a dialog window)
- Ignores the `encodingType`
- Ignores the `targetWidth` and `targetHeight`
- `Camera.MediaType` is not supported.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
#### iOS Quirks
- When using `destinationType.FILE_URI`, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends.
- When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter.
- When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture.
#### Tizen Quirks
- options not supported
- always returns a FILE URI
#### Windows Phone 7 and 8 Quirks
- Ignores the `allowEdit` parameter.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
- Ignores the `saveToPhotoAlbum` parameter. IMPORTANT: All images taken with the 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].
- Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.
[android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html
[web_activities]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
[wp8_bug]: https://issues.apache.org/jira/browse/CB-2083
[msdn_wp8_docs]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx
## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails <a name="sample"></a>
@@ -619,7 +499,7 @@ function setOptions(srcType) {
encodingType: Camera.EncodingType.JPEG,
mediaType: Camera.MediaType.PICTURE,
allowEdit: true,
correctOrientation: true //Corrects Android orientation quirks
correctOrientation: true
}
return options;
}
@@ -659,12 +539,6 @@ function displayImage(imgUri) {
}
```
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.
```html
<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 *">
```
## Take a Picture and Return Thumbnails (Resize the Picture) <a name="getThumbnails"></a>
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).
@@ -694,23 +568,25 @@ function openCamera(selection) {
## Select a File from the Picture Library <a name="selectFile"></a>
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.
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.PHOTOLIBRARY`. 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.
```js
function openFilePicker(selection) {
var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
var srcType = Camera.PictureSourceType.PHOTOLIBRARY;
var options = setOptions(srcType);
var func = createNewFileEntry;
navigator.camera.getPicture(function cameraSuccess(imageUri) {
// Do something
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
navigator.camera.getPicture(
// success callback
(imageUri) => {
// Do something
},
// error callback
(error) => {
console.debug("Unable to obtain picture: " + error, "app");
},
options);
}
```
@@ -721,7 +597,7 @@ Resizing a file selected with the file picker works just like resizing using the
```js
function openFilePicker(selection) {
var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
var srcType = Camera.PictureSourceType.PHOTOLIBRARY;
var options = setOptions(srcType);
var func = createNewFileEntry;
@@ -732,22 +608,24 @@ function openFilePicker(selection) {
options.targetWidth = 100;
}
navigator.camera.getPicture(function cameraSuccess(imageUri) {
// Do something with image
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
navigator.camera.getPicture(
// success callback
(imageUri) {
// Do something with image
},
// error callback
(error) => {
console.debug("Unable to obtain picture: " + error, "app");
},
options);
}
```
## Take a picture and get a FileEntry Object <a name="convert"></a>
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).
If you want to do something like copy the image to another location, or upload it somewhere, an `FileEntry` is needed for the returned picture. To do this, 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).
>*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`.
__NOTE:__ You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`.
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.
@@ -755,39 +633,26 @@ Here is the call to `window.resolveLocalFileSystemURL`. The image URI is passed
function getFileEntry(imgUri) {
window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
// Do something with the FileEntry object, like write to it, upload it, etc.
// writeFile(fileEntry, imgUri);
console.log("got file: " + fileEntry.fullPath);
// displayFileData(fileEntry.nativeURL, "Native URL");
// Example 1: Copy to app data directory
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dataDirectoryEntry) {
fileEntry.copyTo(dataDirectoryEntry, "profilePic", onSuccess, onError);
}, onError);
}, function () {
// If don't get the FileEntry (which may happen when testing
// on some emulators), copy to a new FileEntry.
createNewFileEntry(imgUri);
});
}
```
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.
>*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file).
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.
```js
function createNewFileEntry(imgUri) {
window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
// JPEG file
dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) {
// Do something with it, like write to it, upload it, etc.
// writeFile(fileEntry, imgUri);
console.log("got file: " + fileEntry.fullPath);
// displayFileData(fileEntry.fullPath, "File copied to");
}, onErrorCreateFile);
}, onErrorResolveUrl);
// Example 2: Upload it!
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://myserver.com/upload');
xhr.onload = function () {
// All done!
};
xhr.send(this.result);
};
reader.readAsArrayBuffer(file);
}, onError);
}, onError);
}
```

View File

@@ -7,9 +7,9 @@
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@@ -20,6 +20,213 @@
-->
# Release Notes
### 8.0.0 (Oct 30, 2024)
**Breaking Changes:**
* [GH-889](https://github.com/apache/cordova-plugin-camera/pull/889) fix(android): Remove media permissions to make complaint with **Android** 14 requirements (#889)
* [GH-902](https://github.com/apache/cordova-plugin-camera/pull/902) fix(android): return content uris when possible when selecting from gallery (#902)
* [GH-909](https://github.com/apache/cordova-plugin-camera/pull/909) refactor(android): Make WRITE_EXTERNAL_STORAGE optional (#909)
* [GH-910](https://github.com/apache/cordova-plugin-camera/pull/910) fix(android): Return data uris as an URI (#910)
* [GH-911](https://github.com/apache/cordova-plugin-camera/pull/911) fix(ios): Sync camera API return to match **Android** changes (#911)
* [GH-912](https://github.com/apache/cordova-plugin-camera/pull/912) fix(browser): Make data uri be returned as actual URI strings (#912)
**Fixes**:
* [GH-901](https://github.com/apache/cordova-plugin-camera/pull/901) fix(android): Isolate provider access to a subdirectory (#901)
* [GH-915](https://github.com/apache/cordova-plugin-camera/pull/903) fix(android): Improper serialization of image uri in save instance state (#903)
* [GH-904](https://github.com/apache/cordova-plugin-camera/pull/904) fix(android): Use VERSION_CODES instead of hard-coded API literals (#904)
* [GH-915](https://github.com/apache/cordova-plugin-camera/pull/905) fix(android): improper cache path construction during image manipulation (#905)
* [GH-906](https://github.com/apache/cordova-plugin-camera/pull/906) refactor(android): replace image path usage with image uris (#906)
* [GH-915](https://github.com/apache/cordova-plugin-camera/pull/907) refactor(android): remove query img usage (#907)
* [GH-915](https://github.com/apache/cordova-plugin-camera/pull/915) fix!: Remove WRITE_EXTERNAL_PERMISSION (#915)
**CI**:
* [GH-890](https://github.com/apache/cordova-plugin-camera/pull/890) ci(android): Update **Android** CI to be compatible with `cordova-android`@13 (#890)
* [GH-895](https://github.com/apache/cordova-plugin-camera/pull/895) ci: sync workflow with paramedic (#895)
**Documentation**:
* [GH-913](https://github.com/apache/cordova-plugin-camera/pull/913) docs: Revisions for v8 public API changes with the return string formats of getPicture (#913)
**Other**:
* [GH-898](https://github.com/apache/cordova-plugin-camera/pull/898) chore: Update eslint config to 5.1.0 (#898)
* [GH-914](https://github.com/apache/cordova-plugin-camera/pull/914) deprecation: allowEdit (#914)
### 7.0.0 (Sep 06, 2023)
**Breaking Changes:**
* [GH-848](https://github.com/apache/cordova-plugin-camera/pull/848) fix!: remove deprecated platforms
* [GH-844](https://github.com/apache/cordova-plugin-camera/pull/844) feat(android)!: Android 13 support
**Fixes:**
* [GH-827](https://github.com/apache/cordova-plugin-camera/pull/827) fix(android): set `applicationId`
* [GH-810](https://github.com/apache/cordova-plugin-camera/pull/810) fix(browser): use `navigator.mediaDevices.getUserMedia`
* [GH-712](https://github.com/apache/cordova-plugin-camera/pull/712) fix(ios): preserving `EXIF` data
* [GH-780](https://github.com/apache/cordova-plugin-camera/pull/780) fix(android): update queries in `plugin.xml`
**Chores, Dependencies, Docs:**
* [GH-850](https://github.com/apache/cordova-plugin-camera/pull/850) chore: remove windows/osx from `plugin.xml`
* [GH-849](https://github.com/apache/cordova-plugin-camera/pull/849) chore: Update `SUPPORT_QUESTION.md` template
* [GH-831](https://github.com/apache/cordova-plugin-camera/pull/831) chore(android): Cleanup obsolete `BuildConfig` comments
* [GH-846](https://github.com/apache/cordova-plugin-camera/pull/846) dep(dev)!: bump `@cordova/eslint-config@5.0`
* [GH-800](https://github.com/apache/cordova-plugin-camera/pull/800) dep(npm): bump package-lock v2 w/ rebuild
* [GH-808](https://github.com/apache/cordova-plugin-camera/pull/808) docs(README): Document `ANDROIDX_CORE_VERSION` variable
**CI:**
* [GH-851](https://github.com/apache/cordova-plugin-camera/pull/851) ci(gh-action): sync with `paramedic` configs
* [GH-835](https://github.com/apache/cordova-plugin-camera/pull/835) ci(android): Drop API 22 & 31. Added API 24 & 33
* [GH-804](https://github.com/apache/cordova-plugin-camera/pull/804) ci: sync workflow with `paramedic`
* [GH-798](https://github.com/apache/cordova-plugin-camera/pull/798) ci(android): update java requirement for `cordova-android@11`
* [GH-770](https://github.com/apache/cordova-plugin-camera/pull/770) ci(ios): update workflow w/ iOS 15
* [GH-766](https://github.com/apache/cordova-plugin-camera/pull/766) ci: remove old ci workflow
* [GH-765](https://github.com/apache/cordova-plugin-camera/pull/765) ci: add action-badge
* [GH-764](https://github.com/apache/cordova-plugin-camera/pull/764) ci: remove `travis` & `appveyor`
* [GH-762](https://github.com/apache/cordova-plugin-camera/pull/762) ci: add `gh-actions` workflows
### 6.0.0 (Aug 19, 2021)
**Feature:**
* [GH-751](https://github.com/apache/cordova-plugin-camera/pull/751) feat(android)!: support **AndroidX**
* [GH-750](https://github.com/apache/cordova-plugin-camera/pull/750) feat(android): bump `cordova-android` requirements for `10.x`
* [GH-731](https://github.com/apache/cordova-plugin-camera/pull/731) feat(android): encode `heic` format to `EncodingType` for webview display [#711](https://github.com/apache/cordova-plugin-camera/issues/711)
* [GH-684](https://github.com/apache/cordova-plugin-camera/pull/684) feat(android): `sdk-30` package visibility support
**Fix:**
* [GH-687](https://github.com/apache/cordova-plugin-camera/pull/687) fix(android): return exception message (where it exists)
* [GH-585](https://github.com/apache/cordova-plugin-camera/pull/585) fix(android): file path correction if `Uri` authority is `FileProvider`
**Chore & CI:**
* [GH-749](https://github.com/apache/cordova-plugin-camera/pull/749) chore: bump plugin version for next major
* [GH-654](https://github.com/apache/cordova-plugin-camera/pull/654) chore: add release notify action
* [GH-745](https://github.com/apache/cordova-plugin-camera/pull/745) ci(gh-action): added workflow to run tests
### 5.0.3 (Aug 04, 2021)
* [GH-754](https://github.com/apache/cordova-plugin-camera/pull/754) chore: rebuilt `package-lock.json`
* [GH-748](https://github.com/apache/cordova-plugin-camera/pull/748) fix: incorrect version in `package-lock`
* [GH-747](https://github.com/apache/cordova-plugin-camera/pull/747) chore: set the 5.x versions locked to `cordova-android` `<10.0.0`
* [GH-729](https://github.com/apache/cordova-plugin-camera/pull/729) chore(asf): Update GitHub repo metadata
### 5.0.2 (May 11, 2021)
* [GH-728](https://github.com/apache/cordova-plugin-camera/pull/728) plugin release preparation - audit fix
* [GH-700](https://github.com/apache/cordova-plugin-camera/pull/700) Bugfix [issue 665](https://github.com/apache/cordova-plugin-camera/issues/665) - app crashes after taking a picture due to a bug in the camera plugin when app is resumed
* [GH-691](https://github.com/apache/cordova-plugin-camera/pull/691) ci: add node-14.x to workflow (#691)
### 5.0.1 (Nov 04, 2020)
* [GH-686](https://github.com/apache/cordova-plugin-camera/pull/686) chore(android): add missing apache license header
* [GH-685](https://github.com/apache/cordova-plugin-camera/pull/685) fix(ios): correctly append exif on **iOS** 14
* [GH-669](https://github.com/apache/cordova-plugin-camera/pull/669) fix(android): save to photo gallery - fixes issues [#341](https://github.com/apache/cordova-plugin-camera/pull/341) & [#577](https://github.com/apache/cordova-plugin-camera/pull/577)
* [GH-672](https://github.com/apache/cordova-plugin-camera/pull/672) chore: Fix JIRA links in RELEASENOTES.md
* [GH-664](https://github.com/apache/cordova-plugin-camera/pull/664) chore: Update RELEASENOTES
### 5.0.0 (Sep 14, 2020)
* [GH-648](https://github.com/apache/cordova-plugin-camera/pull/648) ci(travis): update osx xcode image
* [GH-637](https://github.com/apache/cordova-plugin-camera/pull/637) breaking: remove `NATIVE_URI` DestinationType
* [GH-628](https://github.com/apache/cordova-plugin-camera/pull/628) breaking: bump project requirements
* [GH-634](https://github.com/apache/cordova-plugin-camera/pull/634) chore: remove deprecated `file-transfer` plugin
* [GH-632](https://github.com/apache/cordova-plugin-camera/pull/632) fix(android): return error if file url is null
* [GH-510](https://github.com/apache/cordova-plugin-camera/pull/510) fix(android): use provider prefix to avoid conflicts other plugin providers
* [GH-617](https://github.com/apache/cordova-plugin-camera/pull/617) breaking(android): stop using `CordovaUri` helper class
* [GH-630](https://github.com/apache/cordova-plugin-camera/pull/630) chore: add `package-lock.json`
* [GH-631](https://github.com/apache/cordova-plugin-camera/pull/631) chore(package): use short notation
* [GH-629](https://github.com/apache/cordova-plugin-camera/pull/629) feat: migrate to `@cordova/eslint-config@3.x`
* [GH-626](https://github.com/apache/cordova-plugin-camera/pull/626) ci: fix additional tests
* [GH-627](https://github.com/apache/cordova-plugin-camera/pull/627) breaking: bump version 5.0.0-dev
* [GH-612](https://github.com/apache/cordova-plugin-camera/pull/612) fix(ios): `tempFilePath` called twice if using `CameraUsesGeolocation`
* [GH-588](https://github.com/apache/cordova-plugin-camera/pull/588) Cache images in device storage, devices have enough space now.
* [GH-508](https://github.com/apache/cordova-plugin-camera/pull/508) docs(readme): app renamed to Google Photos
* chore(asf): update git notification settings
* [GH-580](https://github.com/apache/cordova-plugin-camera/pull/580) fix(ios): return copy of video when picking from gallery on **iOS** 13
* Update CONTRIBUTING.md
* [GH-551](https://github.com/apache/cordova-plugin-camera/pull/551) Fix UI API called on a background thread
* [GH-576](https://github.com/apache/cordova-plugin-camera/pull/576) ci: updates Node.js versions
* [GH-575](https://github.com/apache/cordova-plugin-camera/pull/575) chore(npm): adds ignore list
* [GH-513](https://github.com/apache/cordova-plugin-camera/pull/513) docs(README): remove confusing comment
* [GH-512](https://github.com/apache/cordova-plugin-camera/pull/512) docs(README): remove orphan **Windows** phone 7 note
* [GH-306](https://github.com/apache/cordova-plugin-camera/pull/306) ImagePicker returning same image
### 4.1.0 (Jun 27, 2019)
- docs: remove outdated test docs translations ([`06dc38f`](https://github.com/apache/cordova-plugin-camera/commit/06dc38f))
- build: remove `.ratignore` file that is not needed any more ([`5dc9527`](https://github.com/apache/cordova-plugin-camera/commit/5dc9527))
- chore: fix repo and issue urls and license in package.json and plugin.xml ([`cad8bd1`](https://github.com/apache/cordova-plugin-camera/commit/cad8bd1))
- fix: temporarily remove Appium tests to unbreak CI ([#468](https://github.com/apache/cordova-plugin-camera/issues/468)) ([`19d8e2f`](https://github.com/apache/cordova-plugin-camera/commit/19d8e2f))
- ci(travis): Update Travis CI configuration for new paramedic ([#455](https://github.com/apache/cordova-plugin-camera/issues/455)) ([`cffd0ac`](https://github.com/apache/cordova-plugin-camera/commit/cffd0ac))
- fix(android): Fix NullPointerException error on some Android phones ([#429](https://github.com/apache/cordova-plugin-camera/issues/429)) ([`295e928`](https://github.com/apache/cordova-plugin-camera/commit/295e928))
- ci: Update CI Environment Setup for Node.js 6 ([#438](https://github.com/apache/cordova-plugin-camera/issues/438)) ([`fae190e`](https://github.com/apache/cordova-plugin-camera/commit/fae190e))
- refactor(android): Enhancement: Camera plugin code cleanup ([#425](https://github.com/apache/cordova-plugin-camera/issues/425)) ([`a13665d`](https://github.com/apache/cordova-plugin-camera/commit/a13665d))
- fix(android): Exif data lost on many cases ([#331](https://github.com/apache/cordova-plugin-camera/issues/331)) ([`81b878d`](https://github.com/apache/cordova-plugin-camera/commit/81b878d))
- chore(github): Add or update GitHub pull request and issue template ([`b261d31`](https://github.com/apache/cordova-plugin-camera/commit/b261d31))
- fix(ios): fixes UIImagePickerController cancel handling for iOS11+ ([#377](https://github.com/apache/cordova-plugin-camera/issues/377)) ([`24c8b6c`](https://github.com/apache/cordova-plugin-camera/commit/24c8b6c))
- docs: Remove deprecated platforms from docs ([#394](https://github.com/apache/cordova-plugin-camera/issues/394)) ([`7ddb3df`](https://github.com/apache/cordova-plugin-camera/commit/7ddb3df))
- fix(android): return DATA_URL for ALLMEDIA if it's an image ([#382](https://github.com/apache/cordova-plugin-camera/issues/382)) ([`60e7795`](https://github.com/apache/cordova-plugin-camera/commit/60e7795))
- refactor(ios): [CB-13813](https://issues.apache.org/jira/browse/CB-13813): Remove old iOS code ([#381](https://github.com/apache/cordova-plugin-camera/issues/381)) ([`ce77aab`](https://github.com/apache/cordova-plugin-camera/commit/ce77aab))
- feat(ios): [CB-13865](https://issues.apache.org/jira/browse/CB-13865): (Ipad) Making popover Window Size configurable using popoverOptions - imagePicker ([#314](https://github.com/apache/cordova-plugin-camera/issues/314)) ([`cd72047`](https://github.com/apache/cordova-plugin-camera/commit/cd72047))
- chore(types): [CB-13837](https://issues.apache.org/jira/browse/CB-13837): fix TypeScript Definition for CameraPopoverOptions ([#379](https://github.com/apache/cordova-plugin-camera/issues/379)) ([`86b0bf2`](https://github.com/apache/cordova-plugin-camera/commit/86b0bf2))
- docs(android): clarify android quirk of cameraDirection ([`a5a3d88`](https://github.com/apache/cordova-plugin-camera/commit/a5a3d88), [`bfbe4a1`](https://github.com/apache/cordova-plugin-camera/commit/bfbe4a1))
- chore(release): Bump minor version ([#370](https://github.com/apache/cordova-plugin-camera/issues/370)) ([`eed4433`](https://github.com/apache/cordova-plugin-camera/commit/eed4433))
- build: Remove automatic README generation ([#365](https://github.com/apache/cordova-plugin-camera/issues/365)) ([`07e8574`](https://github.com/apache/cordova-plugin-camera/commit/07e8574))
- docs: remove JIRA link ([`bcb26fb`](https://github.com/apache/cordova-plugin-camera/commit/bcb26fb))
- ci(travis): also accept terms for android sdk `android-27` ([`a346212`](https://github.com/apache/cordova-plugin-camera/commit/a346212))
- docs: remove outdated docs translations that haven't been touched for 3 years ([`403682b`](https://github.com/apache/cordova-plugin-camera/commit/403682b))
- fix(android): [CB-14097](https://issues.apache.org/jira/browse/CB-14097): Fix crash when selecting some files with getPicture ([#322](https://github.com/apache/cordova-plugin-camera/issues/322)) ([`5c23b65`](https://github.com/apache/cordova-plugin-camera/commit/5c23b65))
- fix(browser): [CB-13384](https://issues.apache.org/jira/browse/CB-13384): Added deprecation of video.src compatibility ([#288](https://github.com/apache/cordova-plugin-camera/issues/288)) ([`5163d38`](https://github.com/apache/cordova-plugin-camera/commit/5163d38))
- fix(browser): Remove audio flag from getUserMedia ([#284](https://github.com/apache/cordova-plugin-camera/issues/284)) ([`36343a8`](https://github.com/apache/cordova-plugin-camera/commit/36343a8))
- docs: replace warning emoji with warning unicode ([#317](https://github.com/apache/cordova-plugin-camera/issues/317)) ([`ead7d5e`](https://github.com/apache/cordova-plugin-camera/commit/ead7d5e))
- feat(android): Update engines to use variables ([#323](https://github.com/apache/cordova-plugin-camera/issues/323)) ([`6899c5e`](https://github.com/apache/cordova-plugin-camera/commit/6899c5e))
- feat(android): [CB-14017](https://issues.apache.org/jira/browse/CB-14017): Make com.android.support:support-v4 version configurable ([#318](https://github.com/apache/cordova-plugin-camera/issues/318)) ([`e334656`](https://github.com/apache/cordova-plugin-camera/commit/e334656))
- refactor(android): [CB-14047](https://issues.apache.org/jira/browse/CB-14047): CameraLauncher: Replacing Repeated String literals with final variables ([#319](https://github.com/apache/cordova-plugin-camera/issues/319)) ([`5ec121b`](https://github.com/apache/cordova-plugin-camera/commit/5ec121b))
- fix(windows): [CB-11714](https://issues.apache.org/jira/browse/CB-11714): added extra check for content-type in savePhoto() without options.targetWidth/Height ([#242](https://github.com/apache/cordova-plugin-camera/issues/242)) ([`a201722`](https://github.com/apache/cordova-plugin-camera/commit/a201722), [`dc73954`](https://github.com/apache/cordova-plugin-camera/commit/dc73954), [`dca4b9c`](https://github.com/apache/cordova-plugin-camera/commit/dca4b9c), [`c1b9772`](https://github.com/apache/cordova-plugin-camera/commit/c1b9772), [`eb57b02`](https://github.com/apache/cordova-plugin-camera/commit/eb57b02))
### 4.0.3 (Apr 12, 2018)
* [CB-12593](https://issues.apache.org/jira/browse/CB-12593) **Android** Fix potential `FileProvider` conflicts
* Fix a mistake in the examples of usage descriptions (#313)
* CB-13854(ios): fix Camera opens in portrait orientation on iphones
* [CB-13415](https://issues.apache.org/jira/browse/CB-13415) **Android** Importing corrupt images using the Camera plugin crashes the app
### 4.0.2 (Jan 24, 2018)
* [CB-13781](https://issues.apache.org/jira/browse/CB-13781) (android) Fixed permissions request on **Android** 8 to save a photo into the photo album
* [CB-13747](https://issues.apache.org/jira/browse/CB-13747) Add build-tools-26.0.2 to travis
### 4.0.1 (Dec 27, 2017)
* CB-13701Fix to allow 4.0.0 version install
### 4.0.0 (Dec 15, 2017)
* [CB-13661](https://issues.apache.org/jira/browse/CB-13661) Remove deprecated platforms
### 3.0.0 (Nov 06, 2017)
* Added `cordova-OSX` support
* [CB-13515](https://issues.apache.org/jira/browse/CB-13515) (all): Add 'protective' entry to `cordovaDependencies`
* [CB-13332](https://issues.apache.org/jira/browse/CB-13332) (iOS): document `NSPhotoLibraryAddUsageDescription`
* [CB-13264](https://issues.apache.org/jira/browse/CB-13264) (iOS): Remove **iOS** usage descriptions
* [CB-13473](https://issues.apache.org/jira/browse/CB-13473) (CI) Removed **Browser** builds from AppVeyor
* [CB-13446](https://issues.apache.org/jira/browse/CB-13446) Sync template with previous doc changes
* [CB-13294](https://issues.apache.org/jira/browse/CB-13294) Removed `cordova-plugin-compat`
* [CB-13299](https://issues.apache.org/jira/browse/CB-13299) (CI) Fix **Android** builds
* [CB-12985](https://issues.apache.org/jira/browse/CB-12985) setup `eslint` and removed `jshint`
* [CB-13028](https://issues.apache.org/jira/browse/CB-13028) (CI) **Browser** builds on Travis and AppVeyor
* [CB-13002](https://issues.apache.org/jira/browse/CB-13002) (Android, **iOS**) Fix occasional Appium tests failures
* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds
* [CB-12991](https://issues.apache.org/jira/browse/CB-12991) (CI) Updated CI badges
* [CB-12964](https://issues.apache.org/jira/browse/CB-12964) (android) Fix of bug when Pictures folder did not exist.
* [CB-12982](https://issues.apache.org/jira/browse/CB-12982) (Android, **iOS**) Appium tests: try to create a session harder
* [CB-12682](https://issues.apache.org/jira/browse/CB-12682) (ios, **Android**): changes cancel error message to be consistent for **iOS** **Android**
* [CB-12764](https://issues.apache.org/jira/browse/CB-12764) (android) Adapt Appium tests for **Android** 7
* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`.
### 2.4.1 (Apr 27, 2017)
* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Updated build badges in `README`
* [CB-12650](https://issues.apache.org/jira/browse/CB-12650) Fix manual test for uploading image

View File

@@ -1,672 +0,0 @@
/*jshint node: true, jasmine: true */
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
// these tests are meant to be executed by Cordova ParaMedic Appium runner
// you can find it here: https://github.com/apache/cordova-paramedic/
// it is not necessary to do a full CI setup to run these tests
// Run:
// node cordova-paramedic/main.js --platform android --plugin cordova-plugin-camera --skipMainTests --target <emulator name>
// Please note only Android 5.1 and 4.4 are supported at this point.
'use strict';
var wdHelper = global.WD_HELPER;
var screenshotHelper = global.SCREENSHOT_HELPER;
var wd = wdHelper.getWD();
var cameraConstants = require('../../www/CameraConstants');
var cameraHelper = require('../helpers/cameraHelper');
var MINUTE = 60 * 1000;
var BACK_BUTTON = 4;
var DEFAULT_SCREEN_WIDTH = 360;
var DEFAULT_SCREEN_HEIGHT = 567;
var DEFAULT_WEBVIEW_CONTEXT = 'WEBVIEW';
var PROMISE_PREFIX = 'appium_camera_promise_';
var CONTEXT_NATIVE_APP = 'NATIVE_APP';
describe('Camera tests Android.', function () {
var driver;
// the name of webview context, it will be changed to match needed context if there are named ones:
var webviewContext = DEFAULT_WEBVIEW_CONTEXT;
// this indicates that the device library has the test picture:
var isTestPictureSaved = false;
// we need to know the screen width and height to properly click on an image in the gallery:
var screenWidth = DEFAULT_SCREEN_WIDTH;
var screenHeight = DEFAULT_SCREEN_HEIGHT;
// promise count to use in promise ID
var promiseCount = 0;
// determine if Appium session is created successfully
var appiumSessionStarted = false;
// determine if camera is present on the device/emulator
var cameraAvailable = false;
// determine if emulator is within a range of acceptable resolutions able to run these tests
var isResolutionBad = true;
// a path to the image we add to the gallery before test run
var fillerImagePath;
function getNextPromiseId() {
promiseCount += 1;
return getCurrentPromiseId();
}
function getCurrentPromiseId() {
return PROMISE_PREFIX + promiseCount;
}
function gracefullyFail(error) {
fail(error);
return driver
.quit()
.then(function () {
return getDriver();
});
}
// combinines specified options in all possible variations
// you can add more options to test more scenarios
function generateOptions() {
var sourceTypes = [
cameraConstants.PictureSourceType.CAMERA,
cameraConstants.PictureSourceType.PHOTOLIBRARY
];
var destinationTypes = cameraConstants.DestinationType;
var encodingTypes = cameraConstants.EncodingType;
var allowEditOptions = [ true, false ];
var correctOrientationOptions = [ true, false ];
return cameraHelper.generateSpecs(sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions);
}
// invokes Camera.getPicture() with the specified options
// and goes through all UI interactions unless 'skipUiInteractions' is true
function getPicture(options, skipUiInteractions) {
var promiseId = getNextPromiseId();
if (!options) {
options = {};
}
return driver
.context(webviewContext)
.execute(cameraHelper.getPicture, [options, promiseId])
.context(CONTEXT_NATIVE_APP)
.then(function () {
if (skipUiInteractions) {
return;
}
// selecting a picture from gallery
if (options.hasOwnProperty('sourceType') &&
(options.sourceType === cameraConstants.PictureSourceType.PHOTOLIBRARY ||
options.sourceType === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM)) {
var tapTile = new wd.TouchAction();
var swipeRight = new wd.TouchAction();
tapTile
.tap({
x: Math.round(screenWidth / 4),
y: Math.round(screenHeight / 4)
});
swipeRight
.press({x: 10, y: Math.round(screenHeight / 4)})
.wait(300)
.moveTo({x: Math.round(screenWidth - (screenWidth / 8)), y: 0})
.wait(1500)
.release()
.wait(1000);
if (options.allowEdit) {
return driver
// always wait before performing touchAction
.sleep(7000)
.performTouchAction(tapTile);
}
return driver
.waitForElementByAndroidUIAutomator('new UiSelector().text("Gallery");', 20000)
.fail(function () {
// If the Gallery button is not present, swipe right to reveal the Gallery button!
return driver
.performTouchAction(swipeRight)
.waitForElementByAndroidUIAutomator('new UiSelector().text("Gallery");', 20000)
})
.click()
// always wait before performing touchAction
.sleep(7000)
.performTouchAction(tapTile);
}
// taking a picture from camera
return driver
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*shutter.*")', MINUTE / 2)
.click()
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*done.*")', MINUTE / 2)
.click();
})
.then(function () {
if (skipUiInteractions) {
return;
}
if (options.allowEdit) {
return driver
.waitForElementByAndroidUIAutomator('new UiSelector().text("Save")', MINUTE)
.click();
}
})
.fail(function (failure) {
throw failure;
});
}
// checks if the picture was successfully taken
// if shouldLoad is falsy, ensures that the error callback was called
function checkPicture(shouldLoad, options) {
if (!options) {
options = {};
}
return driver
.context(webviewContext)
.setAsyncScriptTimeout(MINUTE / 2)
.executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options])
.then(function (result) {
if (shouldLoad) {
if (result !== 'OK') {
fail(result);
}
} else if (result.indexOf('ERROR') === -1) {
throw 'Unexpected success callback with result: ' + result;
}
});
}
// deletes the latest image from the gallery
function deleteImage() {
var holdTile = new wd.TouchAction();
holdTile
.press({x: Math.round(screenWidth / 4), y: Math.round(screenHeight / 5)})
.wait(1000)
.release();
return driver
// always wait before performing touchAction
.sleep(7000)
.performTouchAction(holdTile)
.elementByAndroidUIAutomator('new UiSelector().text("Delete")')
.then(function (element) {
return element
.click()
.elementByAndroidUIAutomator('new UiSelector().text("OK")')
.click();
}, function () {
// couldn't find Delete menu item. Possibly there is no image.
return driver;
});
}
function getDriver() {
driver = wdHelper.getDriver('Android');
return driver.getWebviewContext()
.then(function(context) {
webviewContext = context;
return driver.context(webviewContext);
})
.waitForDeviceReady()
.injectLibraries()
.then(function () {
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
return driver
.then(function () { return getPicture(options, true); })
.context(CONTEXT_NATIVE_APP)
// case insensitive select, will be handy with Android 7 support
.elementByXPath('//android.widget.Button[translate(@text, "alow", "ALOW")="ALLOW"]')
.click()
.fail(function noAlert() { })
.deviceKeyEvent(BACK_BUTTON)
.sleep(2000)
.elementById('action_bar_title')
.then(function () {
// success means we're still in native app
return driver
.deviceKeyEvent(BACK_BUTTON);
}, function () {
// error means we're already in webview
return driver;
});
})
.then(function () {
// doing it inside a function because otherwise
// it would not hook up to the webviewContext var change
// in the first methods of this chain
return driver.context(webviewContext);
})
.deleteFillerImage(fillerImagePath)
.then(function () {
fillerImagePath = null;
})
.addFillerImage()
.then(function (result) {
if (result && result.indexOf('ERROR:') === 0) {
throw new Error(result);
} else {
fillerImagePath = result;
}
});
}
function recreateSession() {
return driver
.quit()
.finally(function () {
return getDriver();
});
}
function tryRunSpec(spec) {
return driver
.then(spec)
.fail(function () {
return recreateSession()
.then(spec)
.fail(function() {
return recreateSession()
.then(spec);
});
})
.fail(gracefullyFail);
}
// produces a generic spec function which
// takes a picture with specified options
// and then verifies it
function generateSpec(options) {
return function () {
return driver
.then(function () {
return getPicture(options);
})
.then(function () {
return checkPicture(true, options);
});
};
}
function checkSession(done, skipResolutionCheck) {
if (!appiumSessionStarted) {
fail('Failed to start a session ' + (lastFailureReason ? lastFailureReason : ''));
done();
}
if (!skipResolutionCheck && isResolutionBad) {
fail('The resolution of this target device is not within the appropriate range of width: blah-blah and height: bleh-bleh. The target\'s current resolution is: ' + isResolutionBad);
}
}
function checkCamera(pending) {
if (!cameraAvailable) {
pending('This test requires a functioning camera on the Android device/emulator, and this test suite\'s functional camera test failed on your target environment.');
}
}
afterAll(function (done) {
checkSession(done);
driver
.quit()
.done(done);
}, MINUTE);
it('camera.ui.util configuring driver and starting a session', function (done) {
getDriver()
.then(function () {
appiumSessionStarted = true;
}, fail)
.done(done);
}, 10 * MINUTE);
it('camera.ui.util determine screen dimensions', function (done) {
checkSession(done, /*skipResolutionCheck?*/ true); // skip the resolution check here since we are about to find out in this spec!
driver
.context(CONTEXT_NATIVE_APP)
.getWindowSize()
.then(function (size) {
screenWidth = Number(size.width);
screenHeight = Number(size.height);
isResolutionBad = false;
/*
TODO: what are acceptable resolution values?
need to check what the emulators used in CI return.
and also what local device definitions work and dont
*/
})
.done(done);
}, MINUTE);
it('camera.ui.util determine camera availability', function (done) {
checkSession(done);
var opts = {
sourceType: cameraConstants.PictureSourceType.CAMERA,
saveToPhotoAlbum: false
};
return driver
.then(function () {
return getPicture(opts);
})
.then(function () {
cameraAvailable = true;
}, function () {
return recreateSession();
})
.done(done);
}, 5 * MINUTE);
describe('Specs.', function () {
// getPicture() with saveToPhotoLibrary = true
it('camera.ui.spec.1 Saving a picture to the photo library', function (done) {
checkSession(done);
checkCamera(pending);
var spec = generateSpec({
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.CAMERA,
saveToPhotoAlbum: true
});
tryRunSpec(spec)
.then(function () {
isTestPictureSaved = true;
})
.done(done);
}, 10 * MINUTE);
// getPicture() with mediaType: VIDEO, sourceType: PHOTOLIBRARY
it('camera.ui.spec.2 Selecting only videos', function (done) {
checkSession(done);
var spec = function () {
var options = { sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
mediaType: cameraConstants.MediaType.VIDEO };
return driver
.then(function () {
return getPicture(options, true);
})
.context(CONTEXT_NATIVE_APP)
.then(function () {
// try to find "Gallery" menu item
// if there's none, the gallery should be already opened
return driver
.waitForElementByAndroidUIAutomator('new UiSelector().text("Gallery")', 20000)
.then(function (element) {
return element.click();
}, function () {
return driver;
});
})
.then(function () {
// if the gallery is opened on the videos page,
// there should be a "Choose video" caption
return driver
.elementByAndroidUIAutomator('new UiSelector().text("Choose video")')
.fail(function () {
throw 'Couldn\'t find a "Choose video" element.';
});
})
.deviceKeyEvent(BACK_BUTTON)
.elementByAndroidUIAutomator('new UiSelector().text("Gallery")')
.deviceKeyEvent(BACK_BUTTON)
.finally(function () {
return driver
.elementById('action_bar_title')
.then(function () {
// success means we're still in native app
return driver
.deviceKeyEvent(BACK_BUTTON)
// give native app some time to close
.sleep(2000)
// try again! because every ~30th build
// on Sauce Labs this backbutton doesn't work
.elementById('action_bar_title')
.then(function () {
// success means we're still in native app
return driver
.deviceKeyEvent(BACK_BUTTON);
}, function () {
// error means we're already in webview
return driver;
});
}, function () {
// error means we're already in webview
return driver;
});
});
};
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
// getPicture(), then dismiss
// wait for the error callback to be called
it('camera.ui.spec.3 Dismissing the camera', function (done) {
checkSession(done);
checkCamera(pending);
var spec = function () {
var options = {
quality: 50,
allowEdit: true,
sourceType: cameraConstants.PictureSourceType.CAMERA,
destinationType: cameraConstants.DestinationType.FILE_URI
};
return driver
.then(function () {
return getPicture(options, true);
})
.context(CONTEXT_NATIVE_APP)
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*cancel.*")', MINUTE / 2)
.click()
.then(function () {
return checkPicture(false);
});
};
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
// getPicture(), then take picture but dismiss the edit
// wait for the error callback to be called
it('camera.ui.spec.4 Dismissing the edit', function (done) {
checkSession(done);
checkCamera(pending);
var spec = function () {
var options = {
quality: 50,
allowEdit: true,
sourceType: cameraConstants.PictureSourceType.CAMERA,
destinationType: cameraConstants.DestinationType.FILE_URI
};
return driver
.then(function () {
return getPicture(options, true);
})
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*shutter.*")', MINUTE / 2)
.click()
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*done.*")', MINUTE / 2)
.click()
.waitForElementByAndroidUIAutomator('new UiSelector().resourceIdMatches(".*discard.*")', MINUTE / 2)
.click()
.then(function () {
return checkPicture(false);
});
};
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
it('camera.ui.spec.5 Verifying target image size, sourceType=CAMERA', function (done) {
checkSession(done);
checkCamera(pending);
var spec = generateSpec({
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.CAMERA,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
});
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
it('camera.ui.spec.6 Verifying target image size, sourceType=PHOTOLIBRARY', function (done) {
checkSession(done);
var spec = generateSpec({
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
});
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
it('camera.ui.spec.7 Verifying target image size, sourceType=CAMERA, DestinationType=NATIVE_URI', function (done) {
checkSession(done);
checkCamera(pending);
var spec = generateSpec({
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.CAMERA,
destinationType: cameraConstants.DestinationType.NATIVE_URI,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
});
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
it('camera.ui.spec.8 Verifying target image size, sourceType=PHOTOLIBRARY, DestinationType=NATIVE_URI', function (done) {
checkSession(done);
var spec = generateSpec({
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
destinationType: cameraConstants.DestinationType.NATIVE_URI,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
});
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
it('camera.ui.spec.9 Verifying target image size, sourceType=CAMERA, DestinationType=NATIVE_URI, quality=100', function (done) {
checkSession(done);
checkCamera(pending);
var spec = generateSpec({
quality: 100,
allowEdit: true,
sourceType: cameraConstants.PictureSourceType.CAMERA,
destinationType: cameraConstants.DestinationType.NATIVE_URI,
saveToPhotoAlbum: false,
targetWidth: 305,
targetHeight: 305
});
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
it('camera.ui.spec.10 Verifying target image size, sourceType=PHOTOLIBRARY, DestinationType=NATIVE_URI, quality=100', function (done) {
checkSession(done);
var spec = generateSpec({
quality: 100,
allowEdit: true,
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
destinationType: cameraConstants.DestinationType.NATIVE_URI,
saveToPhotoAlbum: false,
targetWidth: 305,
targetHeight: 305
});
tryRunSpec(spec).done(done);
}, 10 * MINUTE);
// combine various options for getPicture()
generateOptions().forEach(function (spec) {
it('camera.ui.spec.11.' + spec.id + ' Combining options. ' + spec.description, function (done) {
checkSession(done);
if (spec.options.sourceType == cameraConstants.PictureSourceType.CAMERA) {
checkCamera(pending);
}
var s = generateSpec(spec.options);
tryRunSpec(s).done(done);
}, 10 * MINUTE);
});
it('camera.ui.util Delete filler picture from device library', function (done) {
driver
.context(webviewContext)
.deleteFillerImage(fillerImagePath)
.done(done);
}, MINUTE);
it('camera.ui.util Delete taken picture from device library', function (done) {
checkSession(done);
if (!isTestPictureSaved) {
// couldn't save test picture earlier, so nothing to delete here
done();
return;
}
// delete exactly one latest picture
// this should be the picture we've taken in the first spec
driver
.context(CONTEXT_NATIVE_APP)
.deviceKeyEvent(BACK_BUTTON)
.sleep(1000)
.deviceKeyEvent(BACK_BUTTON)
.sleep(1000)
.deviceKeyEvent(BACK_BUTTON)
.elementById('Apps')
.click()
.then(function () {
return driver
.elementByXPath('//android.widget.Button[@text="OK"]')
.click()
.fail(function () {
// no cling is all right
// it is not a brand new emulator, then
});
})
.elementByAndroidUIAutomator('new UiSelector().text("Gallery")')
.click()
.elementByAndroidUIAutomator('new UiSelector().textContains("Pictures")')
.click()
.then(deleteImage)
.deviceKeyEvent(BACK_BUTTON)
.sleep(1000)
.deviceKeyEvent(BACK_BUTTON)
.sleep(1000)
.deviceKeyEvent(BACK_BUTTON)
.fail(fail)
.finally(done);
}, 3 * MINUTE);
});
});

View File

@@ -1,308 +0,0 @@
/*jshint node: true */
/* global Q, resolveLocalFileSystemURL, Camera, cordova */
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
'use strict';
var cameraConstants = require('../../www/CameraConstants');
function findKeyByValue(set, value) {
for (var k in set) {
if (set.hasOwnProperty(k)) {
if (set[k] == value) {
return k;
}
}
}
return undefined;
}
function getDescription(spec) {
var desc = '';
desc += 'sourceType: ' + findKeyByValue(cameraConstants.PictureSourceType, spec.options.sourceType);
desc += ', destinationType: ' + findKeyByValue(cameraConstants.DestinationType, spec.options.destinationType);
desc += ', encodingType: ' + findKeyByValue(cameraConstants.EncodingType, spec.options.encodingType);
desc += ', allowEdit: ' + spec.options.allowEdit.toString();
desc += ', correctOrientation: ' + spec.options.correctOrientation.toString();
return desc;
}
module.exports.generateSpecs = function (sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions) {
var destinationType,
sourceType,
encodingType,
allowEdit,
correctOrientation,
specs = [],
id = 1;
for (destinationType in destinationTypes) {
if (destinationTypes.hasOwnProperty(destinationType)) {
for (sourceType in sourceTypes) {
if (sourceTypes.hasOwnProperty(sourceType)) {
for (encodingType in encodingTypes) {
if (encodingTypes.hasOwnProperty(encodingType)) {
for (allowEdit in allowEditOptions) {
if (allowEditOptions.hasOwnProperty(allowEdit)) {
for (correctOrientation in correctOrientationOptions) {
// if taking picture from photolibrary, don't vary 'correctOrientation' option
if ((sourceTypes[sourceType] === cameraConstants.PictureSourceType.PHOTOLIBRARY ||
sourceTypes[sourceType] === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM) &&
correctOrientation === true) { continue; }
var spec = {
'id': id++,
'options': {
'destinationType': destinationTypes[destinationType],
'sourceType': sourceTypes[sourceType],
'encodingType': encodingTypes[encodingType],
'allowEdit': allowEditOptions[allowEdit],
'saveToPhotoAlbum': false,
'correctOrientation': correctOrientationOptions[correctOrientation]
}
};
spec.description = getDescription(spec);
specs.push(spec);
}
}
}
}
}
}
}
}
}
return specs;
};
// calls getPicture() and saves the result in promise
// note that this function is executed in the context of tested app
// and not in the context of tests
module.exports.getPicture = function (opts, pid) {
if (navigator._appiumPromises[pid - 1]) {
navigator._appiumPromises[pid - 1] = null;
}
navigator._appiumPromises[pid] = Q.defer();
navigator.camera.getPicture(function (result) {
navigator._appiumPromises[pid].resolve(result);
}, function (err) {
navigator._appiumPromises[pid].reject(err);
}, opts);
};
// verifies taken picture when the promise is resolved,
// calls a callback with 'OK' if everything is good,
// calls a callback with 'ERROR: <error message>' if something is wrong
// note that this function is executed in the context of tested app
// and not in the context of tests
module.exports.checkPicture = function (pid, options, cb) {
var isIos = cordova.platformId === "ios";
var isAndroid = cordova.platformId === "android";
// skip image type check if it's unmodified on Android:
// https://github.com/apache/cordova-plugin-camera/#android-quirks-1
var skipFileTypeCheckAndroid = isAndroid && options.quality === 100 &&
!options.targetWidth && !options.targetHeight &&
!options.correctOrientation;
// Skip image type check if destination is NATIVE_URI and source - device's photoalbum
// https://github.com/apache/cordova-plugin-camera/#ios-quirks-1
var skipFileTypeCheckiOS = isIos && options.destinationType === Camera.DestinationType.NATIVE_URI &&
(options.sourceType === Camera.PictureSourceType.PHOTOLIBRARY ||
options.sourceType === Camera.PictureSourceType.SAVEDPHOTOALBUM);
var skipFileTypeCheck = skipFileTypeCheckAndroid || skipFileTypeCheckiOS;
var desiredType = 'JPEG';
var mimeType = 'image/jpeg';
if (options.encodingType === Camera.EncodingType.PNG) {
desiredType = 'PNG';
mimeType = 'image/png';
}
function errorCallback(msg) {
if (msg.hasOwnProperty('message')) {
msg = msg.message;
}
cb('ERROR: ' + msg);
}
// verifies the image we get from plugin
function verifyResult(result) {
if (result.length === 0) {
errorCallback('The result is empty.');
return;
} else if (isIos && options.destinationType === Camera.DestinationType.NATIVE_URI && result.indexOf('assets-library:') !== 0) {
errorCallback('Expected "' + result.substring(0, 150) + '"to start with "assets-library:"');
return;
} else if (isIos && options.destinationType === Camera.DestinationType.FILE_URI && result.indexOf('file:') !== 0) {
errorCallback('Expected "' + result.substring(0, 150) + '"to start with "file:"');
return;
}
try {
window.atob(result);
// if we got here it is a base64 string (DATA_URL)
result = "data:" + mimeType + ";base64," + result;
} catch (e) {
// not DATA_URL
if (options.destinationType === Camera.DestinationType.DATA_URL) {
errorCallback('Expected ' + result.substring(0, 150) + 'not to be DATA_URL');
return;
}
}
try {
if (result.indexOf('file:') === 0 ||
result.indexOf('content:') === 0 ||
result.indexOf('assets-library:') === 0) {
if (!window.resolveLocalFileSystemURL) {
errorCallback('Cannot read file. Please install cordova-plugin-file to fix this.');
return;
}
resolveLocalFileSystemURL(result, function (entry) {
if (skipFileTypeCheck) {
displayFile(entry);
} else {
verifyFile(entry);
}
}, function (err) {
errorCallback(err);
});
} else {
displayImage(result);
}
} catch (e) {
errorCallback(e);
}
}
// verifies that the file type matches the requested type
function verifyFile(entry) {
try {
var reader = new FileReader();
reader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = '';
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
var actualType = 'unknown';
switch (header) {
case "89504e47":
actualType = 'PNG';
break;
case 'ffd8ffe0':
case 'ffd8ffe1':
case 'ffd8ffe2':
actualType = 'JPEG';
break;
}
if (actualType === desiredType) {
displayFile(entry);
} else {
errorCallback('File type mismatch. Expected ' + desiredType + ', got ' + actualType);
}
};
reader.onerror = function (e) {
errorCallback(e);
};
entry.file(function (file) {
reader.readAsArrayBuffer(file);
}, function (e) {
errorCallback(e);
});
} catch (e) {
errorCallback(e);
}
}
// reads the file, then displays the image
function displayFile(entry) {
function onFileReceived(file) {
var reader = new FileReader();
reader.onerror = function (e) {
errorCallback(e);
};
reader.onloadend = function (evt) {
displayImage(evt.target.result);
};
reader.readAsDataURL(file);
}
entry.file(onFileReceived, function (e) {
errorCallback(e);
});
}
function displayImage(image) {
try {
var imgEl = document.getElementById('camera_test_image');
if (!imgEl) {
imgEl = document.createElement('img');
imgEl.id = 'camera_test_image';
document.body.appendChild(imgEl);
}
var timedOut = false;
var loadTimeout = setTimeout(function () {
timedOut = true;
imgEl.src = '';
errorCallback('The image did not load: ' + image.substring(0, 150));
}, 10000);
var done = function (status) {
if (!timedOut) {
clearTimeout(loadTimeout);
imgEl.src = '';
cb(status);
}
};
imgEl.onload = function () {
try {
// aspect ratio is preserved so only one dimension should match
if ((typeof options.targetWidth === 'number' && imgEl.naturalWidth !== options.targetWidth) &&
(typeof options.targetHeight === 'number' && imgEl.naturalHeight !== options.targetHeight))
{
done('ERROR: Wrong image size: ' + imgEl.naturalWidth + 'x' + imgEl.naturalHeight +
'. Requested size: ' + options.targetWidth + 'x' + options.targetHeight);
} else {
done('OK');
}
} catch (e) {
errorCallback(e);
}
};
imgEl.src = image;
} catch (e) {
errorCallback(e);
}
}
navigator._appiumPromises[pid].promise
.then(function (result) {
verifyResult(result);
})
.fail(function (e) {
errorCallback(e);
});
};

View File

@@ -1,489 +0,0 @@
/*jshint node: true, jasmine: true */
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
// these tests are meant to be executed by Cordova Paramedic test runner
// you can find it here: https://github.com/apache/cordova-paramedic/
// it is not necessary to do a full CI setup to run these tests
// just run "node cordova-paramedic/main.js --platform ios --plugin cordova-plugin-camera"
'use strict';
var wdHelper = global.WD_HELPER;
var screenshotHelper = global.SCREENSHOT_HELPER;
var isDevice = global.DEVICE;
var cameraConstants = require('../../www/CameraConstants');
var cameraHelper = require('../helpers/cameraHelper');
var MINUTE = 60 * 1000;
var DEFAULT_WEBVIEW_CONTEXT = 'WEBVIEW_1';
var PROMISE_PREFIX = 'appium_camera_promise_';
var CONTEXT_NATIVE_APP = 'NATIVE_APP';
describe('Camera tests iOS.', function () {
var driver;
var webviewContext = DEFAULT_WEBVIEW_CONTEXT;
// promise count to use in promise ID
var promiseCount = 0;
// going to set this to false if session is created successfully
var failedToStart = true;
// points out which UI automation to use
var isXCUI = false;
// spec counter to restart the session
var specsRun = 0;
function getNextPromiseId() {
promiseCount += 1;
return getCurrentPromiseId();
}
function getCurrentPromiseId() {
return PROMISE_PREFIX + promiseCount;
}
function gracefullyFail(error) {
fail(error);
return driver
.quit()
.then(function () {
return getDriver();
});
}
// generates test specs by combining all the specified options
// you can add more options to test more scenarios
function generateOptions() {
var sourceTypes = cameraConstants.PictureSourceType;
var destinationTypes = cameraConstants.DestinationType;
var encodingTypes = cameraConstants.EncodingType;
var allowEditOptions = [ true, false ];
var correctOrientationOptions = [ true, false ];
return cameraHelper.generateSpecs(sourceTypes, destinationTypes, encodingTypes, allowEditOptions, correctOrientationOptions);
}
function usePicture() {
return driver
.elementByXPath('//*[@label="Use"]')
.click()
.fail(function () {
if (isXCUI) {
return driver
.waitForElementByAccessibilityId('Choose', MINUTE / 3)
.click();
}
// For some reason "Choose" element is not clickable by standard Appium methods on iOS <= 9
return wdHelper.tapElementByXPath('//UIAButton[@label="Choose"]', driver);
});
}
function clickPhoto() {
if (isXCUI) {
// iOS >=10
return driver
.context(CONTEXT_NATIVE_APP)
.elementsByXPath('//XCUIElementTypeCell')
.then(function(photos) {
if (photos.length == 0) {
return driver
.sleep(0) // driver.source is not a function o.O
.source()
.then(function (src) {
console.log(src);
gracefullyFail('Couldn\'t find an image to click');
});
}
// intentionally clicking the second photo here
// the first one is not clickable for some reason
return photos[1].click();
});
}
// iOS <10
return driver
.elementByXPath('//UIACollectionCell')
.click();
}
function getPicture(options, cancelCamera, skipUiInteractions) {
var promiseId = getNextPromiseId();
if (!options) {
options = {};
}
return driver
.context(webviewContext)
.execute(cameraHelper.getPicture, [options, promiseId])
.context(CONTEXT_NATIVE_APP)
.then(function () {
if (skipUiInteractions) {
return;
}
if (options.hasOwnProperty('sourceType') && options.sourceType === cameraConstants.PictureSourceType.PHOTOLIBRARY) {
return driver
.waitForElementByAccessibilityId('Camera Roll', MINUTE / 2)
.click()
.then(function () {
return clickPhoto();
})
.then(function () {
if (!options.allowEdit) {
return driver;
}
return usePicture();
});
}
if (options.hasOwnProperty('sourceType') && options.sourceType === cameraConstants.PictureSourceType.SAVEDPHOTOALBUM) {
return clickPhoto()
.then(function () {
if (!options.allowEdit) {
return driver;
}
return usePicture();
});
}
if (cancelCamera) {
return driver
.waitForElementByAccessibilityId('Cancel', MINUTE / 2)
.click();
}
return driver
.waitForElementByAccessibilityId('Take Picture', MINUTE / 2)
.click()
.waitForElementByAccessibilityId('Use Photo', MINUTE / 2)
.click();
})
.fail(fail);
}
// checks if the picture was successfully taken
// if shouldLoad is falsy, ensures that the error callback was called
function checkPicture(shouldLoad, options) {
if (!options) {
options = {};
}
return driver
.context(webviewContext)
.setAsyncScriptTimeout(MINUTE / 2)
.executeAsync(cameraHelper.checkPicture, [getCurrentPromiseId(), options])
.then(function (result) {
if (shouldLoad) {
if (result !== 'OK') {
fail(result);
}
} else if (result.indexOf('ERROR') === -1) {
throw 'Unexpected success callback with result: ' + result;
}
});
}
// takes a picture with the specified options
// and then verifies it
function runSpec(options, done, pending) {
if (options.sourceType === cameraConstants.PictureSourceType.CAMERA && !isDevice) {
pending('Camera is not available on iOS simulator');
}
checkSession(done);
specsRun += 1;
return driver
.then(function () {
return getPicture(options);
})
.then(function () {
return checkPicture(true, options);
})
.fail(gracefullyFail);
}
function getDriver() {
failedToStart = true;
driver = wdHelper.getDriver('iOS');
return wdHelper.getWebviewContext(driver)
.then(function(context) {
webviewContext = context;
return driver.context(webviewContext);
})
.then(function () {
return wdHelper.waitForDeviceReady(driver);
})
.then(function () {
return wdHelper.injectLibraries(driver);
})
.sessionCapabilities()
.then(function (caps) {
var platformVersion = parseFloat(caps.platformVersion);
isXCUI = platformVersion >= 10.0;
})
.then(function () {
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
return driver
.then(function () { return getPicture(options, false, true); })
.context(CONTEXT_NATIVE_APP)
.acceptAlert()
.then(function alertDismissed() {
// TODO: once we move to only XCUITest-based (which is force on you in either iOS 10+ or Xcode 8+)
// UI tests, we will have to:
// a) remove use of autoAcceptAlerts appium capability since it no longer functions in XCUITest
// b) can remove this entire then() clause, as we do not need to explicitly handle the acceptAlert
// failure callback, since we will be guaranteed to hit the permission dialog on startup.
}, function noAlert() {
// in case the contacts permission alert never showed up: no problem, don't freak out.
// This can happen if:
// a) The application-under-test already had photos permissions granted to it
// b) Appium's autoAcceptAlerts capability is provided (and functioning)
})
.elementByAccessibilityId('Cancel', 10000)
.click();
})
.then(function () {
failedToStart = false;
});
}
function checkSession(done) {
if (failedToStart) {
fail('Failed to start a session');
done();
}
}
it('camera.ui.util configure driver and start a session', function (done) {
getDriver()
.fail(fail)
.done(done);
}, 15 * MINUTE);
describe('Specs.', function () {
afterEach(function (done) {
if (specsRun >= 15) {
specsRun = 0;
// we need to restart the session regularly because for some reason
// when running against iOS 10 simulator on SauceLabs,
// Appium cannot handle more than ~20 specs at one session
// the error would be as follows:
// "Could not proxy command to remote server. Original error: Error: connect ECONNREFUSED 127.0.0.1:8100"
checkSession(done);
return driver
.quit()
.then(function () {
return getDriver();
})
.done(done);
} else {
done();
}
}, 15 * MINUTE);
// getPicture() with mediaType: VIDEO, sourceType: PHOTOLIBRARY
it('camera.ui.spec.1 Selecting only videos', function (done) {
checkSession(done);
specsRun += 1;
var options = { sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
mediaType: cameraConstants.MediaType.VIDEO };
driver
// skip ui unteractions
.then(function () { return getPicture(options, false, true); })
.waitForElementByXPath('//*[contains(@label,"Videos")]', MINUTE / 2)
.elementByAccessibilityId('Cancel')
.click()
.fail(gracefullyFail)
.done(done);
}, 7 * MINUTE);
// getPicture(), then dismiss
// wait for the error callback to be called
it('camera.ui.spec.2 Dismissing the camera', function (done) {
checkSession(done);
if (!isDevice) {
pending('Camera is not available on iOS simulator');
}
specsRun += 1;
var options = { sourceType: cameraConstants.PictureSourceType.CAMERA,
saveToPhotoAlbum: false };
driver
.then(function () {
return getPicture(options, true);
})
.then(function () {
return checkPicture(false);
})
.fail(gracefullyFail)
.done(done);
}, 7 * MINUTE);
it('camera.ui.spec.3 Verifying target image size, sourceType=CAMERA', function (done) {
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.CAMERA,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.4 Verifying target image size, sourceType=SAVEDPHOTOALBUM', function (done) {
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.5 Verifying target image size, sourceType=PHOTOLIBRARY', function (done) {
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.6 Verifying target image size, sourceType=CAMERA, destinationType=FILE_URL', function (done) {
// remove this line if you don't mind the tests leaving a photo saved on device
pending('Cannot prevent iOS from saving the picture to photo library');
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.CAMERA,
destinationType: cameraConstants.DestinationType.FILE_URL,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.7 Verifying target image size, sourceType=SAVEDPHOTOALBUM, destinationType=FILE_URL', function (done) {
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: cameraConstants.DestinationType.FILE_URL,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.8 Verifying target image size, sourceType=PHOTOLIBRARY, destinationType=FILE_URL', function (done) {
var options = {
quality: 50,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
destinationType: cameraConstants.DestinationType.FILE_URL,
saveToPhotoAlbum: false,
targetWidth: 210,
targetHeight: 210
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.9 Verifying target image size, sourceType=CAMERA, destinationType=FILE_URL, quality=100', function (done) {
// remove this line if you don't mind the tests leaving a photo saved on device
pending('Cannot prevent iOS from saving the picture to photo library');
var options = {
quality: 100,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.CAMERA,
destinationType: cameraConstants.DestinationType.FILE_URL,
saveToPhotoAlbum: false,
targetWidth: 305,
targetHeight: 305
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.10 Verifying target image size, sourceType=SAVEDPHOTOALBUM, destinationType=FILE_URL, quality=100', function (done) {
var options = {
quality: 100,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: cameraConstants.DestinationType.FILE_URL,
saveToPhotoAlbum: false,
targetWidth: 305,
targetHeight: 305
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
it('camera.ui.spec.11 Verifying target image size, sourceType=PHOTOLIBRARY, destinationType=FILE_URL, quality=100', function (done) {
var options = {
quality: 100,
allowEdit: false,
sourceType: cameraConstants.PictureSourceType.PHOTOLIBRARY,
destinationType: cameraConstants.DestinationType.FILE_URL,
saveToPhotoAlbum: false,
targetWidth: 305,
targetHeight: 305
};
runSpec(options, done, pending).done(done);
}, 7 * MINUTE);
// combine various options for getPicture()
generateOptions().forEach(function (spec) {
it('camera.ui.spec.12.' + spec.id + ' Combining options. ' + spec.description, function (done) {
// remove this check if you don't mind the tests leaving a photo saved on device
if (spec.options.sourceType === cameraConstants.PictureSourceType.CAMERA &&
spec.options.destinationType === cameraConstants.DestinationType.NATIVE_URI) {
pending('Skipping: cannot prevent iOS from saving the picture to photo library and cannot delete it. ' +
'For more info, see iOS quirks here: https://github.com/apache/cordova-plugin-camera#ios-quirks-1');
}
runSpec(spec.options, done, pending).done(done);
}, 7 * MINUTE);
});
});
it('camera.ui.util Destroy the session', function (done) {
checkSession(done);
driver
.quit()
.done(done);
}, 5 * MINUTE);
});

View File

@@ -1,421 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
Dieses Plugin definiert eine globale `navigator.camera`-Objekt, das eine API für Aufnahmen und für die Auswahl der Bilder aus dem System-Image-Library bietet.
Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## Installation
cordova plugin add cordova-plugin-camera
## API
* Kamera
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* navigator.camera.cleanup
## navigator.camera.getPicture
Nimmt ein Foto mit der Kamera, oder ein Foto aus dem Gerät Bildergalerie abgerufen. Das Bild wird an den Erfolg-Rückruf als base64-codierte `String` oder als URI für die Image-Datei übergeben. Die Methode selbst gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Datei-Auswahl-Popover neu zu positionieren.
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### Beschreibung
Die `camera.getPicture`-Funktion öffnet das Gerät Standard-Kamera-Anwendung, die Benutzern ermöglicht, Bilder ausrichten. Dieses Verhalten tritt in der Standardeinstellung, wenn `Camera.sourceType` `Camera.PictureSourceType.CAMERA` entspricht. Sobald der Benutzer die Fotoschnäpper, die Kameraanwendung geschlossen wird und die Anwendung wird wiederhergestellt.
Wenn `Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` oder `Camera.PictureSourceType.SAVEDPHOTOALBUM` ist, dann wird ein Dialogfeld angezeigt, das Benutzern ermöglicht, ein vorhandenes Bild auszuwählen. Die `camera.getPicture`-Funktion gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Bild-Auswahl-Dialog, z. B. beim ändert sich der Orientierung des Geräts neu positionieren.
Der Rückgabewert wird an die `cameraSuccess`-Callback-Funktion in einem der folgenden Formate, je nach dem angegebenen `cameraOptions` gesendet:
* A `String` mit dem base64-codierte Foto-Bild.
* A `String` , die die Bild-Datei-Stelle auf lokalem Speicher (Standard).
Sie können tun, was Sie wollen, mit dem codierten Bildes oder URI, zum Beispiel:
* Rendern Sie das Bild in ein `<img>` Tag, wie im folgenden Beispiel
* Die Daten lokal zu speichern ( `LocalStorage` , [Lawnchair](http://brianleroux.github.com/lawnchair/), etc..)
* Post die Daten an einen entfernten server
**Hinweis**: Fotoauflösung auf neueren Geräten ist ganz gut. Fotos aus dem Gerät Galerie ausgewählt sind nicht zu einer niedrigeren Qualität herunterskaliert, selbst wenn ein `Qualität`-Parameter angegeben wird. Um Speicherprobleme zu vermeiden, legen Sie `Camera.destinationType` auf `FILE_URI` statt `DATA_URL`.
#### Unterstützte Plattformen
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### Beispiel
Nehmen Sie ein Foto und rufen Sie sie als base64-codierte Bild:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Nehmen Sie ein Foto und rufen Sie das Bild-Datei-Speicherort:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### "Einstellungen" (iOS)
* **CameraUsesGeolocation** (Boolean, Standardwert ist False). Zur Erfassung von JPEGs, auf true festgelegt, um Geolocation-Daten im EXIF-Header zu erhalten. Dies löst einen Antrag auf Geolocation-Berechtigungen, wenn auf True festgelegt.
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon Fire OS Macken
Amazon Fire OS verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird.
#### Android Eigenarten
Android verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird.
#### Browser-Eigenheiten
Fotos können nur als base64-codierte Bild zurückgeben werden.
#### Firefox OS Macken
Kamera-Plugin ist derzeit implementiert mithilfe von [Web-Aktivitäten](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
#### iOS Macken
Einschließlich einer JavaScript-`alert()` entweder Rückruffunktionen kann Probleme verursachen. Wickeln Sie die Warnung innerhalb eine `setTimeout()` erlauben die iOS-Bild-Picker oder Popover vollständig zu schließen, bevor die Warnung angezeigt:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 Macken
Die native Kameraanwendung aufrufen, während das Gerät via Zune angeschlossen ist funktioniert nicht und löst eine Fehler-Callback.
#### Tizen Macken
Tizen unterstützt nur ein `DestinationType` von `Camera.DestinationType.FILE_URI` und ein `SourceType` von `Camera.PictureSourceType.PHOTOLIBRARY`.
## CameraOptions
Optionale Parameter die Kameraeinstellungen anpassen.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
* **Qualität**: Qualität des gespeicherten Bildes, ausgedrückt als ein Bereich von 0-100, wo 100 in der Regel voller Auflösung ohne Verlust aus der Dateikomprimierung ist. Der Standardwert ist 50. *(Anzahl)* (Beachten Sie, dass Informationen über die Kamera Auflösung nicht verfügbar ist.)
* **DestinationType**: Wählen Sie das Format des Rückgabewerts. Der Standardwert ist FILE_URI. Im Sinne `navigator.camera.DestinationType` *(Anzahl)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **SourceType**: Legen Sie die Quelle des Bildes. Der Standardwert ist die Kamera. Im Sinne `navigator.camera.PictureSourceType` *(Anzahl)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **AllowEdit**: einfache Bearbeitung des Bildes vor Auswahl zu ermöglichen. *(Boolesch)*
* **EncodingType**: die zurückgegebene Image-Datei ist Codierung auswählen. Standardwert ist JPEG. Im Sinne `navigator.camera.EncodingType` *(Anzahl)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **TargetWidth**: Breite in Pixel zum Bild skalieren. Muss mit **TargetHeight**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)*
* **TargetHeight**: Höhe in Pixel zum Bild skalieren. Muss mit **TargetWidth**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)*
* **MediaType**: Legen Sie den Typ der Medien zur Auswahl. Funktioniert nur, wenn `PictureSourceType` ist `PHOTOLIBRARY` oder `SAVEDPHOTOALBUM` . Im Sinne `nagivator.camera.MediaType` *(Anzahl)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. STANDARD. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **CorrectOrientation**: Drehen Sie das Bild um die Ausrichtung des Geräts während der Aufnahme zu korrigieren. *(Boolesch)*
* **SaveToPhotoAlbum**: das Bild auf das Fotoalbum auf dem Gerät zu speichern, nach Einnahme. *(Boolesch)*
* **PopoverOptions**: iOS-nur Optionen, die Popover Lage in iPad angeben. In definierten`CameraPopoverOptions`.
* **CameraDirection**: Wählen Sie die Kamera (vorn oder hinten-gerichtete) verwenden. Der Standardwert ist zurück. Im Sinne `navigator.camera.Direction` *(Anzahl)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### Amazon Fire OS Macken
* `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert.
* Ignoriert die `allowEdit` Parameter.
* `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen.
#### Android Eigenarten
* `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert.
* Android verwendet auch die Ernte-Aktivität für AllowEdit, obwohl Ernte sollte arbeiten und das zugeschnittene Bild zurück zu Cordova, das einzige, dass Werke konsequent die gebündelt mit der Google-Plus-Fotos-Anwendung ist tatsächlich zu übergeben. Andere Kulturen funktioniert möglicherweise nicht.
* `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen.
#### BlackBerry 10 Macken
* Ignoriert die `quality` Parameter.
* Ignoriert die `allowEdit` Parameter.
* `Camera.MediaType`wird nicht unterstützt.
* Ignoriert die `correctOrientation` Parameter.
* Ignoriert die `cameraDirection` Parameter.
#### Firefox OS Macken
* Ignoriert die `quality` Parameter.
* `Camera.DestinationType`wird ignoriert, und gleich `1` (Bilddatei-URI)
* Ignoriert die `allowEdit` Parameter.
* Ignoriert die `PictureSourceType` Parameter (Benutzer wählt es in einem Dialogfenster)
* Ignoriert die`encodingType`
* Ignoriert die `targetWidth` und`targetHeight`
* `Camera.MediaType`wird nicht unterstützt.
* Ignoriert die `correctOrientation` Parameter.
* Ignoriert die `cameraDirection` Parameter.
#### iOS Macken
* Legen Sie `quality` unter 50 Speicherfehler auf einigen Geräten zu vermeiden.
* Bei der Verwendung `destinationType.FILE_URI` , Fotos werden im temporären Verzeichnis der Anwendung gespeichert. Den Inhalt des temporären Verzeichnis der Anwendung wird gelöscht, wenn die Anwendung beendet.
#### Tizen Macken
* nicht unterstützte Optionen
* gibt immer einen Datei-URI
#### Windows Phone 7 und 8 Eigenarten
* Ignoriert die `allowEdit` Parameter.
* Ignoriert die `correctOrientation` Parameter.
* Ignoriert die `cameraDirection` Parameter.
* Ignoriert die `saveToPhotoAlbum` Parameter. WICHTIG: Alle Aufnahmen die wp7/8 Cordova-Kamera-API werden immer in Kamerarolle des Telefons kopiert. Abhängig von den Einstellungen des Benutzers könnte dies auch bedeuten, dass das Bild in ihre OneDrive automatisch hochgeladen ist. Dies könnte möglicherweise bedeuten, dass das Bild für ein breiteres Publikum als Ihre Anwendung vorgesehen ist. Wenn diese einen Blocker für Ihre Anwendung, Sie müssen die CameraCaptureTask zu implementieren, wie im Msdn dokumentiert: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> Sie können kommentieren oder Up-Abstimmung das Beiträge zu diesem Thema im [Bugtracker](https://issues.apache.org/jira/browse/CB-2083)
* Ignoriert die `mediaType` -Eigenschaft des `cameraOptions` wie das Windows Phone SDK keine Möglichkeit, Fotothek Videos wählen.
## CameraError
onError-Callback-Funktion, die eine Fehlermeldung bereitstellt.
function(message) {
// Show a helpful message
}
#### Beschreibung
* **Meldung**: die Nachricht wird durch das Gerät systemeigenen Code bereitgestellt. *(String)*
## cameraSuccess
onSuccess Callback-Funktion, die die Bilddaten bereitstellt.
function(imageData) {
// Do something with the image
}
#### Beschreibung
* **CMYK**: Base64-Codierung der Bilddaten, *oder* die Image-Datei-URI, je nach `cameraOptions` in Kraft. *(String)*
#### Beispiel
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Ein Handle für das Dialogfeld "Popover" erstellt von `navigator.camera.getPicture`.
#### Beschreibung
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### Unterstützte Plattformen
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Beispiel
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
nur iOS-Parametern, die Anker-Element Lage und Pfeil Richtung der Popover angeben, bei der Auswahl von Bildern aus einem iPad Bibliothek oder Album.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### Beschreibung
* **X**: x Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **y**: y Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **width**: Breite in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **height**: Höhe in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **arrowDir**: Richtung der Pfeil auf der Popover zeigen sollte. Im Sinne `Camera.PopoverArrowDirection` *(Anzahl)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Beachten Sie, dass die Größe der Popover ändern kann, um die Richtung des Pfeils und Ausrichtung des Bildschirms anzupassen. Achten Sie darauf, um Orientierung zu berücksichtigen, wenn Sie den Anker-Element-Speicherort angeben.
## navigator.camera.cleanup
Entfernt Mittelstufe Fotos von der Kamera aus der vorübergehenden Verwahrung genommen.
navigator.camera.cleanup( cameraSuccess, cameraError );
#### Beschreibung
Fortgeschrittene Image-Dateien, die in vorübergehender Verwahrung gehalten werden, nach dem Aufruf von `camera.getPicture` entfernt. Gilt nur wenn der Wert von `Camera.sourceType` gleich `Camera.PictureSourceType.CAMERA` und `Camera.destinationType` gleich `Camera.DestinationType.FILE_URI`.
#### Unterstützte Plattformen
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Beispiel
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,434 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
Dieses Plugin definiert eine globale `navigator.camera`-Objekt, das eine API für Aufnahmen und für die Auswahl der Bilder aus dem System-Image-Library bietet.
Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## Installation
cordova plugin add cordova-plugin-camera
## navigator.camera.getPicture
Nimmt ein Foto mit der Kamera, oder ein Foto aus dem Gerät Bildergalerie abgerufen. Das Bild wird an den Erfolg-Rückruf als base64-codierte `String` oder als URI für die Image-Datei übergeben. Die Methode selbst gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Datei-Auswahl-Popover neu zu positionieren.
navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions );
### Beschreibung
Die `camera.getPicture`-Funktion öffnet das Gerät Standard-Kamera-Anwendung, die Benutzern ermöglicht, Bilder ausrichten. Dieses Verhalten tritt in der Standardeinstellung, wenn `Camera.sourceType` `Camera.PictureSourceType.CAMERA` entspricht. Sobald der Benutzer die Fotoschnäpper, die Kameraanwendung geschlossen wird und die Anwendung wird wiederhergestellt.
Wenn `Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` oder `Camera.PictureSourceType.SAVEDPHOTOALBUM` ist, dann wird ein Dialogfeld angezeigt, das Benutzern ermöglicht, ein vorhandenes Bild auszuwählen. Die `camera.getPicture`-Funktion gibt ein `CameraPopoverHandle`-Objekt, das verwendet werden kann, um die Bild-Auswahl-Dialog, z. B. beim ändert sich der Orientierung des Geräts neu positionieren.
Der Rückgabewert wird an die `cameraSuccess`-Callback-Funktion in einem der folgenden Formate, je nach dem angegebenen `cameraOptions` gesendet:
* A `String` mit dem base64-codierte Foto-Bild.
* A `String` , die die Bild-Datei-Stelle auf lokalem Speicher (Standard).
Sie können tun, was Sie wollen, mit dem codierten Bildes oder URI, zum Beispiel:
* Rendern Sie das Bild in ein `<img>` Tag, wie im folgenden Beispiel
* Die Daten lokal zu speichern ( `LocalStorage` , [Lawnchair][1], etc..)
* Post die Daten an einen entfernten server
[1]: http://brianleroux.github.com/lawnchair/
**Hinweis**: Fotoauflösung auf neueren Geräten ist ganz gut. Fotos aus dem Gerät Galerie ausgewählt sind nicht zu einer niedrigeren Qualität herunterskaliert, selbst wenn ein `Qualität`-Parameter angegeben wird. Um Speicherprobleme zu vermeiden, legen Sie `Camera.destinationType` auf `FILE_URI` statt `DATA_URL`.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Browser
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### "Einstellungen" (iOS)
* **CameraUsesGeolocation** (Boolean, Standardwert ist False). Zur Erfassung von JPEGs, auf true festgelegt, um Geolocation-Daten im EXIF-Header zu erhalten. Dies löst einen Antrag auf Geolocation-Berechtigungen, wenn auf True festgelegt.
<preference name="CameraUsesGeolocation" value="false" />
### Amazon Fire OS Macken
Amazon Fire OS verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird.
### Android Eigenarten
Android verwendet Absichten zum Starten von der Kamera-Aktivität auf dem Gerät, um Bilder zu erfassen und auf Handys mit wenig Speicher, Cordova Tätigkeit getötet werden kann. In diesem Szenario kann das Bild nicht angezeigt, wenn die Aktivität von Cordova wiederhergestellt wird.
### Browser-Eigenheiten
Fotos können nur als base64-codierte Bild zurückgeben werden.
### Firefox OS Macken
Kamera-Plugin ist derzeit implementiert mithilfe von [Web-Aktivitäten][2].
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### iOS Macken
Einschließlich einer JavaScript-`alert()` entweder Rückruffunktionen kann Probleme verursachen. Wickeln Sie die Warnung innerhalb eine `setTimeout()` erlauben die iOS-Bild-Picker oder Popover vollständig zu schließen, bevor die Warnung angezeigt:
setTimeout(function() {
// do your thing here!
}, 0);
### Windows Phone 7 Macken
Die native Kameraanwendung aufrufen, während das Gerät via Zune angeschlossen ist funktioniert nicht und löst eine Fehler-Callback.
### Tizen Macken
Tizen unterstützt nur ein `DestinationType` von `Camera.DestinationType.FILE_URI` und ein `SourceType` von `Camera.PictureSourceType.PHOTOLIBRARY`.
### Beispiel
Nehmen Sie ein Foto und rufen Sie sie als base64-codierte Bild:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Nehmen Sie ein Foto und rufen Sie das Bild-Datei-Speicherort:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
## CameraOptions
Optionale Parameter die Kameraeinstellungen anpassen.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
### Optionen
* **Qualität**: Qualität des gespeicherten Bildes, ausgedrückt als ein Bereich von 0-100, wo 100 in der Regel voller Auflösung ohne Verlust aus der Dateikomprimierung ist. Der Standardwert ist 50. *(Anzahl)* (Beachten Sie, dass Informationen über die Kamera Auflösung nicht verfügbar ist.)
* **DestinationType**: Wählen Sie das Format des Rückgabewerts. Der Standardwert ist FILE_URI. Im Sinne `navigator.camera.DestinationType` *(Anzahl)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **SourceType**: Legen Sie die Quelle des Bildes. Der Standardwert ist die Kamera. Im Sinne `navigator.camera.PictureSourceType` *(Anzahl)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **AllowEdit**: einfache Bearbeitung des Bildes vor Auswahl zu ermöglichen. *(Boolesch)*
* **EncodingType**: die zurückgegebene Image-Datei ist Codierung auswählen. Standardwert ist JPEG. Im Sinne `navigator.camera.EncodingType` *(Anzahl)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **TargetWidth**: Breite in Pixel zum Bild skalieren. Muss mit **TargetHeight**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)*
* **TargetHeight**: Höhe in Pixel zum Bild skalieren. Muss mit **TargetWidth**verwendet werden. Seitenverhältnis bleibt konstant. *(Anzahl)*
* **MediaType**: Legen Sie den Typ der Medien zur Auswahl. Funktioniert nur, wenn `PictureSourceType` ist `PHOTOLIBRARY` oder `SAVEDPHOTOALBUM` . Im Sinne `nagivator.camera.MediaType` *(Anzahl)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. STANDARD. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **CorrectOrientation**: Drehen Sie das Bild um die Ausrichtung des Geräts während der Aufnahme zu korrigieren. *(Boolesch)*
* **SaveToPhotoAlbum**: das Bild auf das Fotoalbum auf dem Gerät zu speichern, nach Einnahme. *(Boolesch)*
* **PopoverOptions**: iOS-nur Optionen, die Popover Lage in iPad angeben. In definierten`CameraPopoverOptions`.
* **CameraDirection**: Wählen Sie die Kamera (vorn oder hinten-gerichtete) verwenden. Der Standardwert ist zurück. Im Sinne `navigator.camera.Direction` *(Anzahl)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### Amazon Fire OS Macken
* `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert.
* Ignoriert die `allowEdit` Parameter.
* `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen.
### Android Eigenarten
* `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert.
* Ignoriert die `allowEdit` Parameter.
* `Camera.PictureSourceType.PHOTOLIBRARY`und `Camera.PictureSourceType.SAVEDPHOTOALBUM` beide das gleiche Fotoalbum anzuzeigen.
### BlackBerry 10 Macken
* Ignoriert die `quality` Parameter.
* Ignoriert die `allowEdit` Parameter.
* `Camera.MediaType`wird nicht unterstützt.
* Ignoriert die `correctOrientation` Parameter.
* Ignoriert die `cameraDirection` Parameter.
### Firefox OS Macken
* Ignoriert die `quality` Parameter.
* `Camera.DestinationType`wird ignoriert, und gleich `1` (Bilddatei-URI)
* Ignoriert die `allowEdit` Parameter.
* Ignoriert die `PictureSourceType` Parameter (Benutzer wählt es in einem Dialogfenster)
* Ignoriert die`encodingType`
* Ignoriert die `targetWidth` und`targetHeight`
* `Camera.MediaType`wird nicht unterstützt.
* Ignoriert die `correctOrientation` Parameter.
* Ignoriert die `cameraDirection` Parameter.
### iOS Macken
* Legen Sie `quality` unter 50 Speicherfehler auf einigen Geräten zu vermeiden.
* Bei der Verwendung `destinationType.FILE_URI` , Fotos werden im temporären Verzeichnis der Anwendung gespeichert. Den Inhalt des temporären Verzeichnis der Anwendung wird gelöscht, wenn die Anwendung beendet.
### Tizen Macken
* nicht unterstützte Optionen
* gibt immer einen Datei-URI
### Windows Phone 7 und 8 Eigenarten
* Ignoriert die `allowEdit` Parameter.
* Ignoriert die `correctOrientation` Parameter.
* Ignoriert die `cameraDirection` Parameter.
* Ignoriert die `saveToPhotoAlbum` Parameter. WICHTIG: Alle Aufnahmen die wp7/8 Cordova-Kamera-API werden immer in Kamerarolle des Telefons kopiert. Abhängig von den Einstellungen des Benutzers könnte dies auch bedeuten, dass das Bild in ihre OneDrive automatisch hochgeladen ist. Dies könnte möglicherweise bedeuten, dass das Bild für ein breiteres Publikum als Ihre Anwendung vorgesehen ist. Wenn diese einen Blocker für Ihre Anwendung, Sie müssen die CameraCaptureTask zu implementieren, wie im Msdn dokumentiert: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> Sie können kommentieren oder Up-Abstimmung das Beiträge zu diesem Thema im [Bugtracker][3]
* Ignoriert die `mediaType` -Eigenschaft des `cameraOptions` wie das Windows Phone SDK keine Möglichkeit, Fotothek Videos wählen.
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
onError-Callback-Funktion, die eine Fehlermeldung bereitstellt.
function(message) {
// Show a helpful message
}
### Parameter
* **Meldung**: die Nachricht wird durch das Gerät systemeigenen Code bereitgestellt. *(String)*
## cameraSuccess
onSuccess Callback-Funktion, die die Bilddaten bereitstellt.
function(imageData) {
// Do something with the image
}
### Parameter
* **CMYK**: Base64-Codierung der Bilddaten, *oder* die Image-Datei-URI, je nach `cameraOptions` in Kraft. *(String)*
### Beispiel
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Ein Handle für das Dialogfeld "Popover" erstellt von `navigator.camera.getPicture`.
### Methoden
* **SetPosition**: Legen Sie die Position der Popover.
### Unterstützte Plattformen
* iOS
### setPosition
Legen Sie die Position von der Popover.
**Parameter**:
* `cameraPopoverOptions`: die `CameraPopoverOptions` angeben, dass die neue Position
### Beispiel
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
nur iOS-Parametern, die Anker-Element Lage und Pfeil Richtung der Popover angeben, bei der Auswahl von Bildern aus einem iPad Bibliothek oder Album.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
### CameraPopoverOptions
* **X**: x Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **y**: y Pixelkoordinate des Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **width**: Breite in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **height**: Höhe in Pixeln, das Bildschirmelement auf dem der Popover zu verankern. *(Anzahl)*
* **arrowDir**: Richtung der Pfeil auf der Popover zeigen sollte. Im Sinne `Camera.PopoverArrowDirection` *(Anzahl)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Beachten Sie, dass die Größe der Popover ändern kann, um die Richtung des Pfeils und Ausrichtung des Bildschirms anzupassen. Achten Sie darauf, um Orientierung zu berücksichtigen, wenn Sie den Anker-Element-Speicherort angeben.
## navigator.camera.cleanup
Entfernt Mittelstufe Fotos von der Kamera aus der vorübergehenden Verwahrung genommen.
navigator.camera.cleanup( cameraSuccess, cameraError );
### Beschreibung
Fortgeschrittene Image-Dateien, die in vorübergehender Verwahrung gehalten werden, nach dem Aufruf von `camera.getPicture` entfernt. Gilt nur wenn der Wert von `Camera.sourceType` gleich `Camera.PictureSourceType.CAMERA` und `Camera.destinationType` gleich `Camera.DestinationType.FILE_URI`.
### Unterstützte Plattformen
* iOS
### Beispiel
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,411 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
Este plugin define un global `navigator.camera` objeto que proporciona una API para tomar fotografías y por elegir imágenes de biblioteca de imágenes del sistema.
Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento.
document.addEventListener ("deviceready", onDeviceReady, false);
function onDeviceReady() {console.log(navigator.camera)};
## Instalación
cordova plugin add cordova-plugin-camera
## API
* Cámara
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* Navigator.Camera.Cleanup
## navigator.camera.getPicture
Toma una foto con la cámara, o recupera una foto de Galería de imágenes del dispositivo. La imagen se pasa a la devolución de llamada de éxito como un codificado en base64 `String` , o como el URI para el archivo de imagen. El método se devuelve un `CameraPopoverHandle` objeto que puede utilizarse para volver a colocar el popover de selección de archivo.
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### Descripción
El `camera.getPicture` función abre la aplicación de cámara predeterminada del dispositivo que permite a los usuarios ajustar imágenes. Este comportamiento se produce de forma predeterminada, cuando `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` . Una vez que el usuario ajusta la foto, una aplicación de cámara se cierra y se restablecerá la aplicación.
Si `Camera.sourceType` es `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM` , entonces una muestra de diálogo que permite a los usuarios seleccionar una imagen existente. El `camera.getPicture` función devuelve un `CameraPopoverHandle` objeto, que puede utilizarse para volver a colocar el diálogo de selección de imagen, por ejemplo, cuando cambia la orientación del dispositivo.
El valor devuelto es enviado a la `cameraSuccess` función de callback, en uno de los formatos siguientes, dependiendo del objeto `cameraOptions` :
* Una `String` que contiene la imagen codificada en base64.
* Una `String` que representa la ubicación del archivo de imagen en almacenamiento local (por defecto).
Puedes hacer lo que quieras con la imagen codificada o URI, por ejemplo:
* Representar la imagen en una etiqueta de `<img>`, como en el ejemplo siguiente
* Guardar los datos localmente (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
* Enviar los datos a un servidor remoto
**Nota**: resolución de la foto en los nuevos dispositivos es bastante bueno. Fotos seleccionadas de la Galería del dispositivo no son degradadas a una calidad más baja, incluso si un `quality` se especifica el parámetro. Para evitar problemas con la memoria común, establezca `Camera.destinationType` a `FILE_URI` en lugar de`DATA_URL`.
#### Plataformas soportadas
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### Ejemplo
Tomar una foto y recuperarlo como una imagen codificada en base64:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Tomar una foto y recuperar la ubicación del archivo de la imagen:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### Preferencias (iOS)
* **CameraUsesGeolocation** (booleano, el valor predeterminado de false). Para la captura de imágenes JPEG, establecido en true para obtener datos de geolocalización en la cabecera EXIF. Esto activará la solicitud de permisos de geolocalización si establecido en true.
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon fuego OS rarezas
Amazon fuego OS utiliza los intentos para poner en marcha la actividad de la cámara del dispositivo para capturar imágenes y en teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad cordova.
#### Rarezas Android
Android utiliza los intentos para iniciar la actividad de la cámara del dispositivo para capturar imágenes, y en los teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad Cordova.
#### Navegador rarezas
Sólo puede devolver fotos como imagen codificada en base64.
#### Firefox OS rarezas
Cámara plugin actualmente se implementa mediante [Actividades Web](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
#### iOS rarezas
Incluyendo un JavaScript `alert()` en cualquiera de la devolución de llamada funciones pueden causar problemas. Envuelva la alerta dentro de un `setTimeout()` para permitir que el selector de imagen iOS o popover cerrar completamente antes de la alerta se muestra:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 rarezas
Invocando la aplicación de cámara nativa mientras el dispositivo está conectado vía Zune no funciona y desencadena un callback de error.
#### Rarezas Tizen
Tizen sólo es compatible con un `destinationType` de `Camera.DestinationType.FILE_URI` y un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`.
## CameraOptions
Parámetros opcionales para personalizar la configuración de la cámara.
{calidad: destinationType 75,: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.CAMERA, allowEdit: true, encodingType: Camera.EncodingType.JPEG, targetWidth: 100, targetHeight: 100, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: falsa};
* **calidad**: calidad de la imagen guardada, expresada en un rango de 0-100, donde 100 es típicamente resolución sin pérdida de compresión del archivo. El valor predeterminado es 50. *(Número)* (Tenga en cuenta que no está disponible información sobre resolución de la cámara).
* **destinationType**: elegir el formato del valor devuelto. El valor predeterminado es FILE_URI. Definido en `navigator.camera.DestinationType` *(número)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: establecer el origen de la imagen. El valor predeterminado es cámara. Definido en `navigator.camera.PictureSourceType` *(número)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: permite edición sencilla de imagen antes de la selección. *(Booleano)*
* **encodingType**: elegir la codificación del archivo de imagen devuelta. Por defecto es JPEG. Definido en `navigator.camera.EncodingType` *(número)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: ancho en píxeles a escala de la imagen. Debe usarse con **targetHeight**. Proporción se mantiene constante. *(Número)*
* **targetHeight**: altura en píxeles a escala de la imagen. Debe usarse con **targetWidth**. Proporción se mantiene constante. *(Número)*
* **mediaType**: definir el tipo de medios para seleccionar. Sólo funciona cuando `PictureSourceType` es `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definido en `nagivator.camera.MediaType` *(número)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DE FORMA PREDETERMINADA. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: rotar la imagen para corregir la orientación del dispositivo durante la captura. *(Booleano)*
* **saveToPhotoAlbum**: guardar la imagen en el álbum de fotos en el dispositivo después de su captura. *(Booleano)*
* **popoverOptions**: opciones sólo iOS que especifican popover ubicación en iPad. Definido en`CameraPopoverOptions`.
* **cameraDirection**: elegir la cámara para usar (o parte posterior-frontal). El valor predeterminado es atrás. Definido en `navigator.camera.Direction` *(número)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### Amazon fuego OS rarezas
* Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás.
* Ignora el `allowEdit` parámetro.
* `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos.
#### Rarezas Android
* Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás.
* Android también utiliza la actividad de cultivo de allowEdit, aunque cultivo debe trabajar y realmente pasar la imagen recortada a Córdoba, el único que funciona constantemente es el integrado con la aplicación de Google Plus fotos. Otros cultivos pueden no funcionar.
* `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos.
#### BlackBerry 10 rarezas
* Ignora el `quality` parámetro.
* Ignora el `allowEdit` parámetro.
* `Camera.MediaType`No se admite.
* Ignora el `correctOrientation` parámetro.
* Ignora el `cameraDirection` parámetro.
#### Firefox OS rarezas
* Ignora el `quality` parámetro.
* `Camera.DestinationType`se ignora y es igual a `1` (URI del archivo de imagen)
* Ignora el `allowEdit` parámetro.
* Ignora el `PictureSourceType` parámetro (el usuario lo elige en una ventana de diálogo)
* Ignora el`encodingType`
* Ignora el `targetWidth` y`targetHeight`
* `Camera.MediaType`No se admite.
* Ignora el `correctOrientation` parámetro.
* Ignora el `cameraDirection` parámetro.
#### iOS rarezas
* Establecer `quality` por debajo de 50 para evitar errores de memoria en algunos dispositivos.
* Cuando se utiliza `destinationType.FILE_URI` , fotos se guardan en el directorio temporal de la aplicación. El contenido del directorio temporal de la aplicación se eliminará cuando finalice la aplicación.
#### Rarezas Tizen
* opciones no compatibles
* siempre devuelve un identificador URI de archivo
#### Windows Phone 7 y 8 rarezas
* Ignora el `allowEdit` parámetro.
* Ignora el `correctOrientation` parámetro.
* Ignora el `cameraDirection` parámetro.
* Ignora el `saveToPhotoAlbum` parámetro. IMPORTANTE: Todas las imágenes tomadas con la cámara wp7/8 cordova API siempre se copian en rollo de cámara del teléfono. Dependiendo de la configuración del usuario, esto podría significar también que la imagen es auto-subido a su OneDrive. Esto potencialmente podría significar que la imagen está disponible a una audiencia más amplia que su aplicación previsto. Si un bloqueador para su aplicación, usted necesitará aplicar el CameraCaptureTask como se documenta en msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> también puede comentar o votar hasta el tema relacionado en el [issue tracker de](https://issues.apache.org/jira/browse/CB-2083)
* Ignora el `mediaType` propiedad de `cameraOptions` como el SDK de Windows Phone no proporciona una manera para elegir vídeos fototeca.
## CameraError
onError función callback que proporciona un mensaje de error.
function(message) {
// Show a helpful message
}
#### Descripción
* **mensaje**: el mensaje es proporcionado por código nativo del dispositivo. *(String)*
## cameraSuccess
onSuccess función callback que proporciona los datos de imagen.
function(imageData) {
// Do something with the image
}
#### Descripción
* **imageData**: codificación en Base64 de los datos de imagen, *o* el archivo de imagen URI, dependiendo de `cameraOptions` en vigor. *(String)*
#### Ejemplo
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Un identificador para el cuadro de diálogo popover creado por`navigator.camera.getPicture`.
#### Descripción
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### Plataformas soportadas
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Ejemplo
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
Sólo iOS parámetros que especifican la dirección ancla elemento ubicación y la flecha de la popover al seleccionar imágenes de biblioteca o álbum de un iPad.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### Descripción
* **x**: coordenadas de píxeles del elemento de la pantalla en la que anclar el popover x. *(Número)*
* **y**: coordenada píxeles del elemento de la pantalla en la que anclar el popover. *(Número)*
* **anchura**: anchura, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)*
* **altura**: alto, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)*
* **arrowDir**: dirección de la flecha en el popover debe apuntar. Definido en `Camera.PopoverArrowDirection` *(número)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Tenga en cuenta que puede cambiar el tamaño de la popover para ajustar la dirección de la flecha y orientación de la pantalla. Asegúrese de que para tener en cuenta los cambios de orientación cuando se especifica la ubicación del elemento de anclaje.
## Navigator.Camera.Cleanup
Elimina intermedio fotos tomadas por la cámara de almacenamiento temporal.
Navigator.Camera.cleanup (cameraSuccess, cameraError);
#### Descripción
Elimina intermedio archivos de imagen que se mantienen en depósito temporal después de llamar `camera.getPicture` . Se aplica sólo cuando el valor de `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` y el `Camera.destinationType` es igual a`Camera.DestinationType.FILE_URI`.
#### Plataformas soportadas
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Ejemplo
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,391 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
Este plugin define un global `navigator.camera` objeto que proporciona una API para tomar fotografías y por elegir imágenes de biblioteca de imágenes del sistema.
Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento.
document.addEventListener ("deviceready", onDeviceReady, false);
function onDeviceReady() {console.log(navigator.camera)};
## Instalación
Cordova plugin agregar cordova-plugin-camera
## navigator.camera.getPicture
Toma una foto con la cámara, o recupera una foto de Galería de imágenes del dispositivo. La imagen se pasa a la devolución de llamada de éxito como un codificado en base64 `String` , o como el URI para el archivo de imagen. El método se devuelve un `CameraPopoverHandle` objeto que puede utilizarse para volver a colocar el popover de selección de archivo.
navigator.camera.getPicture (cameraSuccess, cameraError, cameraOptions);
### Descripción
El `camera.getPicture` función abre la aplicación de cámara predeterminada del dispositivo que permite a los usuarios ajustar imágenes. Este comportamiento se produce de forma predeterminada, cuando `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` . Una vez que el usuario ajusta la foto, una aplicación de cámara se cierra y se restablecerá la aplicación.
Si `Camera.sourceType` es `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM` , entonces una muestra de diálogo que permite a los usuarios seleccionar una imagen existente. El `camera.getPicture` función devuelve un `CameraPopoverHandle` objeto, que puede utilizarse para volver a colocar el diálogo de selección de imagen, por ejemplo, cuando cambia la orientación del dispositivo.
El valor devuelto es enviado a la `cameraSuccess` función de callback, en uno de los formatos siguientes, dependiendo del objeto `cameraOptions` :
* Una `String` que contiene la imagen codificada en base64.
* Una `String` que representa la ubicación del archivo de imagen en almacenamiento local (por defecto).
Puedes hacer lo que quieras con la imagen codificada o URI, por ejemplo:
* Representar la imagen en una etiqueta de `<img>`, como en el ejemplo siguiente
* Guardar los datos localmente (`LocalStorage`, [Lawnchair][1], etc.)
* Enviar los datos a un servidor remoto
[1]: http://brianleroux.github.com/lawnchair/
**Nota**: resolución de la foto en los nuevos dispositivos es bastante bueno. Fotos seleccionadas de la Galería del dispositivo no son degradadas a una calidad más baja, incluso si un `quality` se especifica el parámetro. Para evitar problemas con la memoria común, establezca `Camera.destinationType` a `FILE_URI` en lugar de`DATA_URL`.
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Explorador
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Preferencias (iOS)
* **CameraUsesGeolocation** (booleano, el valor predeterminado de false). Para la captura de imágenes JPEG, establecido en true para obtener datos de geolocalización en la cabecera EXIF. Esto activará la solicitud de permisos de geolocalización si establecido en true.
<preference name="CameraUsesGeolocation" value="false" />
### Amazon fuego OS rarezas
Amazon fuego OS utiliza los intentos para poner en marcha la actividad de la cámara del dispositivo para capturar imágenes y en teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad cordova.
### Rarezas Android
Android utiliza los intentos para iniciar la actividad de la cámara del dispositivo para capturar imágenes, y en los teléfonos con poca memoria, puede matar la actividad Cordova. En este escenario, la imagen no aparezca cuando se restaura la actividad Cordova.
### Navegador rarezas
Sólo puede devolver fotos como imagen codificada en base64.
### Firefox OS rarezas
Cámara plugin actualmente se implementa mediante [Actividades Web][2].
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### iOS rarezas
Incluyendo un JavaScript `alert()` en cualquiera de la devolución de llamada funciones pueden causar problemas. Envuelva la alerta dentro de un `setTimeout()` para permitir que el selector de imagen iOS o popover cerrar completamente antes de la alerta se muestra:
setTimeout(function() {/ / Haz lo tuyo aquí!}, 0);
### Windows Phone 7 rarezas
Invocando la aplicación de cámara nativa mientras el dispositivo está conectado vía Zune no funciona y desencadena un callback de error.
### Rarezas Tizen
Tizen sólo es compatible con un `destinationType` de `Camera.DestinationType.FILE_URI` y un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`.
### Ejemplo
Tomar una foto y recuperarlo como una imagen codificada en base64:
navigator.camera.getPicture (onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {var imagen = document.getElementById('myImage');
Image.src = "datos: image / jpeg; base64," + imageData;}
function onFail(message) {alert (' falló porque: ' + mensaje);}
Tomar una foto y recuperar la ubicación del archivo de la imagen:
navigator.camera.getPicture (onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {var imagen = document.getElementById('myImage');
Image.src = imageURI;
} function onFail(message) {alert (' falló porque: ' + mensaje);}
## CameraOptions
Parámetros opcionales para personalizar la configuración de la cámara.
{calidad: destinationType 75,: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.CAMERA, allowEdit: true, encodingType: Camera.EncodingType.JPEG, targetWidth: 100, targetHeight: 100, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: falsa};
### Opciones
* **calidad**: calidad de la imagen guardada, expresada en un rango de 0-100, donde 100 es típicamente resolución sin pérdida de compresión del archivo. El valor predeterminado es 50. *(Número)* (Tenga en cuenta que no está disponible información sobre resolución de la cámara).
* **destinationType**: elegir el formato del valor devuelto. El valor predeterminado es FILE_URI. Definido en `navigator.camera.DestinationType` *(número)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: establecer el origen de la imagen. El valor predeterminado es cámara. Definido en `navigator.camera.PictureSourceType` *(número)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: permite edición sencilla de imagen antes de la selección. *(Booleano)*
* **encodingType**: elegir la codificación del archivo de imagen devuelta. Por defecto es JPEG. Definido en `navigator.camera.EncodingType` *(número)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: ancho en píxeles a escala de la imagen. Debe usarse con **targetHeight**. Proporción se mantiene constante. *(Número)*
* **targetHeight**: altura en píxeles a escala de la imagen. Debe usarse con **targetWidth**. Proporción se mantiene constante. *(Número)*
* **mediaType**: definir el tipo de medios para seleccionar. Sólo funciona cuando `PictureSourceType` es `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definido en `nagivator.camera.MediaType` *(número)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DE FORMA PREDETERMINADA. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: rotar la imagen para corregir la orientación del dispositivo durante la captura. *(Booleano)*
* **saveToPhotoAlbum**: guardar la imagen en el álbum de fotos en el dispositivo después de su captura. *(Booleano)*
* **popoverOptions**: opciones sólo iOS que especifican popover ubicación en iPad. Definido en`CameraPopoverOptions`.
* **cameraDirection**: elegir la cámara para usar (o parte posterior-frontal). El valor predeterminado es atrás. Definido en `navigator.camera.Direction` *(número)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### Amazon fuego OS rarezas
* Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás.
* Ignora el `allowEdit` parámetro.
* `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos.
### Rarezas Android
* Cualquier valor de `cameraDirection` da como resultado una foto orientada hacia atrás.
* Ignora el `allowEdit` parámetro.
* `Camera.PictureSourceType.PHOTOLIBRARY` y `Camera.PictureSourceType.SAVEDPHOTOALBUM` Mostrar el mismo álbum de fotos.
### BlackBerry 10 rarezas
* Ignora el `quality` parámetro.
* Ignora el `allowEdit` parámetro.
* `Camera.MediaType`No se admite.
* Ignora el `correctOrientation` parámetro.
* Ignora el `cameraDirection` parámetro.
### Firefox OS rarezas
* Ignora el `quality` parámetro.
* `Camera.DestinationType`se ignora y es igual a `1` (URI del archivo de imagen)
* Ignora el `allowEdit` parámetro.
* Ignora el `PictureSourceType` parámetro (el usuario lo elige en una ventana de diálogo)
* Ignora el`encodingType`
* Ignora el `targetWidth` y`targetHeight`
* `Camera.MediaType`No se admite.
* Ignora el `correctOrientation` parámetro.
* Ignora el `cameraDirection` parámetro.
### iOS rarezas
* Establecer `quality` por debajo de 50 para evitar errores de memoria en algunos dispositivos.
* Cuando se utiliza `destinationType.FILE_URI` , fotos se guardan en el directorio temporal de la aplicación. El contenido del directorio temporal de la aplicación se eliminará cuando finalice la aplicación.
### Rarezas Tizen
* opciones no compatibles
* siempre devuelve un identificador URI de archivo
### Windows Phone 7 y 8 rarezas
* Ignora el `allowEdit` parámetro.
* Ignora el `correctOrientation` parámetro.
* Ignora el `cameraDirection` parámetro.
* Ignora el `saveToPhotoAlbum` parámetro. IMPORTANTE: Todas las imágenes tomadas con la cámara wp7/8 cordova API siempre se copian en rollo de cámara del teléfono. Dependiendo de la configuración del usuario, esto podría significar también que la imagen es auto-subido a su OneDrive. Esto potencialmente podría significar que la imagen está disponible a una audiencia más amplia que su aplicación previsto. Si un bloqueador para su aplicación, usted necesitará aplicar el CameraCaptureTask como se documenta en msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> también puede comentar o votar hasta el tema relacionado en el [issue tracker de][3]
* Ignora el `mediaType` propiedad de `cameraOptions` como el SDK de Windows Phone no proporciona una manera para elegir vídeos fototeca.
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
onError función callback que proporciona un mensaje de error.
function(Message) {/ / Mostrar un mensaje útil}
### Parámetros
* **mensaje**: el mensaje es proporcionado por código nativo del dispositivo. *(String)*
## cameraSuccess
onSuccess función callback que proporciona los datos de imagen.
function(ImageData) {/ / hacer algo con la imagen}
### Parámetros
* **imageData**: codificación en Base64 de los datos de imagen, *o* el archivo de imagen URI, dependiendo de `cameraOptions` en vigor. *(String)*
### Ejemplo
Mostrar imagen / / function cameraCallback(imageData) {var imagen = document.getElementById('myImage');
Image.src = "datos: image / jpeg; base64," + imageData;}
## CameraPopoverHandle
Un identificador para el cuadro de diálogo popover creado por`navigator.camera.getPicture`.
### Métodos
* **setPosition**: establecer la posición de la popover.
### Plataformas soportadas
* iOS
### setPosition
Establecer la posición de la popover.
**Parámetros**:
* `cameraPopoverOptions`: el `CameraPopoverOptions` que especifican la nueva posición
### Ejemplo
var cameraPopoverHandle = navigator.camera.getPicture (onSuccess, onFail, {destinationType: Camera.DestinationType.FILE_URI, sourceType: Camera.PictureSourceType.PHOTOLIBRARY, popoverOptions: CameraPopoverOptions nuevo (300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)});
Vuelva a colocar el popover si cambia la orientación.
Window.onorientationchange = function() {var cameraPopoverOptions = new CameraPopoverOptions (0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
Sólo iOS parámetros que especifican la dirección ancla elemento ubicación y la flecha de la popover al seleccionar imágenes de biblioteca o álbum de un iPad.
{x: 0, y: 32, ancho: 320, altura: 480, arrowDir: Camera.PopoverArrowDirection.ARROW_ANY};
### CameraPopoverOptions
* **x**: coordenadas de píxeles del elemento de la pantalla en la que anclar el popover x. *(Número)*
* **y**: coordenada píxeles del elemento de la pantalla en la que anclar el popover. *(Número)*
* **anchura**: anchura, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)*
* **altura**: alto, en píxeles, del elemento sobre el que anclar el popover pantalla. *(Número)*
* **arrowDir**: dirección de la flecha en el popover debe apuntar. Definido en `Camera.PopoverArrowDirection` *(número)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Tenga en cuenta que puede cambiar el tamaño de la popover para ajustar la dirección de la flecha y orientación de la pantalla. Asegúrese de que para tener en cuenta los cambios de orientación cuando se especifica la ubicación del elemento de anclaje.
## Navigator.Camera.Cleanup
Elimina intermedio fotos tomadas por la cámara de almacenamiento temporal.
Navigator.Camera.cleanup (cameraSuccess, cameraError);
### Descripción
Elimina intermedio archivos de imagen que se mantienen en depósito temporal después de llamar `camera.getPicture` . Se aplica sólo cuando el valor de `Camera.sourceType` es igual a `Camera.PictureSourceType.CAMERA` y el `Camera.destinationType` es igual a`Camera.DestinationType.FILE_URI`.
### Plataformas soportadas
* iOS
### Ejemplo
Navigator.Camera.cleanup (onSuccess, onFail);
function onSuccess() {console.log ("cámara limpieza éxito.")}
function onFail(message) {alert (' falló porque: ' + mensaje);}

View File

@@ -1,378 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
Ce plugin définit un global `navigator.camera` objet qui fournit une API pour la prise de photos et de choisir des images de la bibliothèque d'images du système.
Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement.
document.addEventListener (« deviceready », onDeviceReady, false) ;
function onDeviceReady() {console.log(navigator.camera);}
## Installation
cordova plugin add cordova-plugin-camera
## API
* Appareil photo
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* Navigator.Camera.Cleanup
## navigator.camera.getPicture
Prend une photo à l'aide de la caméra, ou récupère une photo de la Galerie d'images de l'appareil. L'image est passé au rappel succès comme un codage base64 `String` , ou comme l'URI du fichier de l'image. La méthode elle-même retourne un `CameraPopoverHandle` objet qui permet de repositionner le kangourou de sélection de fichier.
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### Description
Le `camera.getPicture` fonction ouvre l'application de caméra par défaut de l'appareil qui permet aux utilisateurs de prendre des photos. Ce comportement se produit par défaut, lorsque `Camera.sourceType` est égal à `Camera.PictureSourceType.CAMERA` . Une fois que l'utilisateur s'enclenche la photo, l'application appareil photo se ferme et l'application est restaurée.
Si `Camera.sourceType` est `Camera.PictureSourceType.PHOTOLIBRARY` ou `Camera.PictureSourceType.SAVEDPHOTOALBUM` , puis un dialogue affiche qui permet aux utilisateurs de sélectionner une image existante. Le `camera.getPicture` retourne un `CameraPopoverHandle` objet, ce qui permet de repositionner le dialogue de sélection d'image, par exemple, lorsque l'orientation de l'appareil change.
La valeur de retour est envoyée à la `cameraSuccess` la fonction de rappel, dans l'un des formats suivants, selon les `cameraOptions` :
* A `String` contenant l'image photo codée en base64.
* A `String` qui représente l'emplacement du fichier image sur le stockage local (par défaut).
Vous pouvez faire ce que vous voulez avec l'image codée ou URI, par exemple :
* Afficher l'image dans un `<img>` tag, comme dans l'exemple ci-dessous
* Enregistrer les données localement ( `LocalStorage` , [poids](http://brianleroux.github.com/lawnchair/), etc..)
* Publier les données sur un serveur distant
**NOTE**: la résolution de Photo sur les nouveaux appareils est assez bonne. Photos sélectionnées de la Galerie de l'appareil ne sont pas réduites à une baisse de la qualité, même si un `quality` paramètre est spécifié. Pour éviter les problèmes de mémoire commun, définissez `Camera.destinationType` à `FILE_URI` au lieu de`DATA_URL`.
#### Plates-formes supportées
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### Exemple
Prendre une photo, puis extrayez-la comme une image codée en base64 :
navigator.camera.getPicture (onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
}) ;
function onSuccess(imageData) {var image = document.getElementById('myImage') ;
image.src = "données : image / jpeg ; base64," + imageData;}
function onFail(message) {alert (' a échoué car: "+ message);}
Prendre une photo et récupérer l'emplacement du fichier de l'image :
navigator.camera.getPicture (onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI }) ;
function onSuccess(imageURI) {var image = document.getElementById('myImage') ;
image.SRC = imageURI ;
} function onFail(message) {alert (' a échoué car: "+ message);}
#### Préférences (iOS)
* **CameraUsesGeolocation** (boolean, par défaut, false). Pour capturer des images JPEG, true pour obtenir des données de géolocalisation dans l'en-tête EXIF. Cela va déclencher une demande d'autorisations de géolocalisation si défini à true.
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon Fire OS Quirks
Amazon Fire OS utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de cordova est restaurée.
#### Quirks Android
Android utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de Cordova est restaurée.
#### Bizarreries navigateur
Peut retourner uniquement les photos comme image codée en base64.
#### Firefox OS Quirks
Appareil photo plugin est actuellement mis en œuvre à l'aide [d'Activités sur le Web](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
#### Notes au sujet d'iOS
Y compris un JavaScript `alert()` dans les deux le rappel fonctions peuvent causer des problèmes. Envelopper l'alerte dans un `setTimeout()` pour permettre le sélecteur d'image iOS ou kangourou pour fermer entièrement avant que l'alerte s'affiche :
setTimeout(function() {/ / faire votre truc ici!}, 0) ;
#### Windows Phone 7 Quirks
Invoquant l'application native caméra alors que l'appareil est connecté via Zune ne fonctionne pas et déclenche un rappel de l'erreur.
#### Bizarreries de paciarelli
Paciarelli prend uniquement en charge un `destinationType` de `Camera.DestinationType.FILE_URI` et un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`.
## CameraOptions
Paramètres optionnels pour personnaliser les réglages de l'appareil.
{qualité : destinationType 75,: Camera.DestinationType.DATA_URL, TypeSource : Camera.PictureSourceType.CAMERA, allowEdit : encodingType vrai,: Camera.EncodingType.JPEG, targetWidth : 100, targetHeight : 100, popoverOptions : CameraPopoverOptions, saveToPhotoAlbum : false} ;
* **qualité**: qualité de l'image enregistrée, exprimée en une gamme de 0 à 100, 100 étant généralement pleine résolution sans perte de compression de fichiers. La valeur par défaut est 50. *(Nombre)* (Notez que les informations sur la résolution de la caméra sont indisponibles).
* **destinationType**: choisissez le format de la valeur de retour. La valeur par défaut est FILE_URI. Définies dans `navigator.camera.DestinationType` *(nombre)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: définissez la source de l'image. La valeur par défaut est la caméra. Définies dans `navigator.camera.PictureSourceType` *(nombre)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: permettre un montage simple d'image avant la sélection. *(Booléen)*
* **encodingType**: choisir le fichier image retournée de codage. Valeur par défaut est JPEG. Définies dans `navigator.camera.EncodingType` *(nombre)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: largeur en pixels de l'image de l'échelle. Doit être utilisé avec **targetHeight**. Aspect ratio reste constant. *(Nombre)*
* **targetHeight**: hauteur en pixels de l'image de l'échelle. Doit être utilisé avec **targetWidth**. Aspect ratio reste constant. *(Nombre)*
* **mediaType**: définir le type de média pour choisir de. Ne fonctionne que quand `PictureSourceType` est `PHOTOLIBRARY` ou `SAVEDPHOTOALBUM` . Définies dans `nagivator.camera.MediaType` *(nombre)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. PAR DÉFAUT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: faire pivoter l'image afin de corriger l'orientation de l'appareil lors de la capture. *(Booléen)*
* **saveToPhotoAlbum**: enregistrer l'image sur l'album photo sur l'appareil après la capture. *(Booléen)*
* **popoverOptions**: iOS uniquement des options qui spécifient l'emplacement de kangourou dans iPad. Défini dans`CameraPopoverOptions`.
* **cameraDirection**: choisissez la caméra à utiliser (ou dos-face). La valeur par défaut est de retour. Définies dans `navigator.camera.Direction` *(nombre)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### Amazon Fire OS Quirks
* Tout `cameraDirection` résultats dans le back-face photo de valeur.
* Ignore la `allowEdit` paramètre.
* `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo.
#### Quirks Android
* Tout `cameraDirection` résultats dans le back-face photo de valeur.
* Android utilise également l'activité de récolte pour allowEdit, même si la récolte doit travailler et transmet en réalité l'image recadrée à Cordoue, le seul que les œuvres sont toujours celui livré avec l'application Google Plus Photos. Autres cultures peuvent ne pas fonctionner.
* `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo.
#### BlackBerry 10 Quirks
* Ignore la `quality` paramètre.
* Ignore la `allowEdit` paramètre.
* `Camera.MediaType`n'est pas pris en charge.
* Ignore la `correctOrientation` paramètre.
* Ignore la `cameraDirection` paramètre.
#### Firefox OS Quirks
* Ignore la `quality` paramètre.
* `Camera.DestinationType`est ignorée et est égal à `1` (URI du fichier image)
* Ignore la `allowEdit` paramètre.
* Ignore la `PictureSourceType` paramètre (utilisateur il choisit dans une fenêtre de dialogue)
* Ignore le`encodingType`
* Ignore la `targetWidth` et`targetHeight`
* `Camera.MediaType`n'est pas pris en charge.
* Ignore la `correctOrientation` paramètre.
* Ignore la `cameraDirection` paramètre.
#### Notes au sujet d'iOS
* La valeur `quality` inférieur à 50 pour éviter les erreurs de mémoire sur certains appareils.
* Lorsque vous utilisez `destinationType.FILE_URI` , les photos sont sauvegardées dans le répertoire temporaire de l'application. Le contenu du répertoire temporaire de l'application est supprimé lorsque l'application se termine.
#### Bizarreries de paciarelli
* options non prises en charge
* retourne toujours un URI de fichier
#### Notes au sujet de Windows Phone 7 et 8
* Ignore la `allowEdit` paramètre.
* Ignore la `correctOrientation` paramètre.
* Ignore la `cameraDirection` paramètre.
* Ignore la `saveToPhotoAlbum` paramètre. IMPORTANT : Toutes les images prises avec la caméra de cordova wp7/8 API sont toujours copiés au rôle d'appareil photo du téléphone. Selon les paramètres de l'utilisateur, cela pourrait également signifier que l'image est auto-téléchargées à leur OneDrive. Potentiellement, cela pourrait signifier que l'image est disponible à un public plus large que votre application destinée. Si ce un bloqueur pour votre application, vous devrez implémenter le CameraCaptureTask tel que documenté sur msdn : <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> vous pouvez aussi commenter ou haut-vote la question connexe dans le [gestionnaire d'incidents](https://issues.apache.org/jira/browse/CB-2083)
* Ignore la `mediaType` propriété de `cameraOptions` comme le kit de développement Windows Phone ne fournit pas un moyen de choisir les vidéos de PHOTOLIBRARY.
## CameraError
fonction de rappel onError qui fournit un message d'erreur.
function(message) {/ / afficher un message utile}
#### Description
* **message**: le message est fourni par du code natif de l'appareil. *(String)*
## cameraSuccess
fonction de rappel onSuccess qui fournit les données d'image.
function(ImageData) {/ / faire quelque chose avec l'image}
#### Description
* **imageData**: codage Base64 de l'image, *ou* le fichier image URI, selon `cameraOptions` en vigueur. *(String)*
#### Exemple
Afficher image / / function cameraCallback(imageData) {var image = document.getElementById('myImage') ;
image.src = "données : image / jpeg ; base64," + imageData;}
## CameraPopoverHandle
Un handle vers la boîte de dialogue de kangourou créé par`navigator.camera.getPicture`.
#### Description
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### Plates-formes supportées
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Exemple
var cameraPopoverHandle = navigator.camera.getPicture (onSuccess, onFail, {destinationType : Camera.DestinationType.FILE_URI, TypeSource : Camera.PictureSourceType.PHOTOLIBRARY, popoverOptions : nouvelle CameraPopoverOptions (300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)}) ;
Repositionner le kangourou si l'orientation change.
Window.onorientationchange = function() {var cameraPopoverOptions = new CameraPopoverOptions (0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) ;
cameraPopoverHandle.setPosition(cameraPopoverOptions) ;
}
## CameraPopoverOptions
iOS uniquement les paramètres qui spécifient la direction ancre élément emplacement et de la flèche de la kangourou lors de la sélection des images de la bibliothèque de l'iPad ou l'album.
{x: 0, y: 32, largeur : 320, hauteur : 480, arrowDir : Camera.PopoverArrowDirection.ARROW_ANY} ;
#### Description
* **x**: coordonnée de pixel de l'élément de l'écran sur lequel ancrer le kangourou x. *(Nombre)*
* **y**: coordonnée de y pixels de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
* **largeur**: largeur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
* **hauteur**: hauteur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
* **arrowDir**: Direction de la flèche sur le kangourou doit pointer. Définies dans `Camera.PopoverArrowDirection` *(nombre)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Notez que la taille de la kangourou peut changer pour s'adapter à la direction de la flèche et l'orientation de l'écran. Assurez-vous que tenir compte des changements d'orientation lors de la spécification de l'emplacement d'élément d'ancrage.
## Navigator.Camera.Cleanup
Supprime les intermédiaires photos prises par la caméra de stockage temporaire.
Navigator.Camera.Cleanup (cameraSuccess, cameraError) ;
#### Description
Supprime les intermédiaires les fichiers image qui sont gardées en dépôt temporaire après avoir appelé `camera.getPicture` . S'applique uniquement lorsque la valeur de `Camera.sourceType` est égale à `Camera.PictureSourceType.CAMERA` et le `Camera.destinationType` est égal à`Camera.DestinationType.FILE_URI`.
#### Plates-formes supportées
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Exemple
Navigator.Camera.Cleanup (onSuccess, onFail) ;
fonction onSuccess() {console.log ("succès de caméra nettoyage.")}
function onFail(message) {alert (' a échoué car: "+ message);}

View File

@@ -1,391 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
Ce plugin définit un global `navigator.camera` objet qui fournit une API pour la prise de photos et de choisir des images de la bibliothèque d'images du système.
Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement.
document.addEventListener (« deviceready », onDeviceReady, false) ;
function onDeviceReady() {console.log(navigator.camera);}
## Installation
Cordova plugin ajouter cordova-plugin-camera
## navigator.camera.getPicture
Prend une photo à l'aide de la caméra, ou récupère une photo de la Galerie d'images de l'appareil. L'image est passé au rappel succès comme un codage base64 `String` , ou comme l'URI du fichier de l'image. La méthode elle-même retourne un `CameraPopoverHandle` objet qui permet de repositionner le kangourou de sélection de fichier.
navigator.camera.getPicture (cameraSuccess, cameraError, cameraOptions) ;
### Description
Le `camera.getPicture` fonction ouvre l'application de caméra par défaut de l'appareil qui permet aux utilisateurs de prendre des photos. Ce comportement se produit par défaut, lorsque `Camera.sourceType` est égal à `Camera.PictureSourceType.CAMERA` . Une fois que l'utilisateur s'enclenche la photo, l'application appareil photo se ferme et l'application est restaurée.
Si `Camera.sourceType` est `Camera.PictureSourceType.PHOTOLIBRARY` ou `Camera.PictureSourceType.SAVEDPHOTOALBUM` , puis un dialogue affiche qui permet aux utilisateurs de sélectionner une image existante. Le `camera.getPicture` retourne un `CameraPopoverHandle` objet, ce qui permet de repositionner le dialogue de sélection d'image, par exemple, lorsque l'orientation de l'appareil change.
La valeur de retour est envoyée à la `cameraSuccess` la fonction de rappel, dans l'un des formats suivants, selon les `cameraOptions` :
* A `String` contenant l'image photo codée en base64.
* A `String` qui représente l'emplacement du fichier image sur le stockage local (par défaut).
Vous pouvez faire ce que vous voulez avec l'image codée ou URI, par exemple :
* Afficher l'image dans un `<img>` tag, comme dans l'exemple ci-dessous
* Enregistrer les données localement ( `LocalStorage` , [poids][1], etc..)
* Publier les données sur un serveur distant
[1]: http://brianleroux.github.com/lawnchair/
**NOTE**: la résolution de Photo sur les nouveaux appareils est assez bonne. Photos sélectionnées de la Galerie de l'appareil ne sont pas réduites à une baisse de la qualité, même si un `quality` paramètre est spécifié. Pour éviter les problèmes de mémoire commun, définissez `Camera.destinationType` à `FILE_URI` au lieu de`DATA_URL`.
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* BlackBerry 10
* Navigateur
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Préférences (iOS)
* **CameraUsesGeolocation** (boolean, par défaut, false). Pour capturer des images JPEG, true pour obtenir des données de géolocalisation dans l'en-tête EXIF. Cela va déclencher une demande d'autorisations de géolocalisation si défini à true.
<preference name="CameraUsesGeolocation" value="false" />
### Amazon Fire OS Quirks
Amazon Fire OS utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de cordova est restaurée.
### Quirks Android
Android utilise des intentions pour lancer l'activité de l'appareil photo sur l'appareil pour capturer des images et sur les téléphones avec peu de mémoire, l'activité de Cordova peut être tuée. Dans ce scénario, l'image peut ne pas apparaître lorsque l'activité de Cordova est restaurée.
### Bizarreries navigateur
Peut retourner uniquement les photos comme image codée en base64.
### Firefox OS Quirks
Appareil photo plugin est actuellement mis en œuvre à l'aide [d'Activités sur le Web][2].
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### iOS Quirks
Y compris un JavaScript `alert()` dans les deux le rappel fonctions peuvent causer des problèmes. Envelopper l'alerte dans un `setTimeout()` pour permettre le sélecteur d'image iOS ou kangourou pour fermer entièrement avant que l'alerte s'affiche :
setTimeout(function() {/ / faire votre truc ici!}, 0) ;
### Windows Phone 7 Quirks
Invoquant l'application native caméra alors que l'appareil est connecté via Zune ne fonctionne pas et déclenche un rappel de l'erreur.
### Bizarreries de paciarelli
Paciarelli prend uniquement en charge un `destinationType` de `Camera.DestinationType.FILE_URI` et un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`.
### Exemple
Prendre une photo, puis extrayez-la comme une image codée en base64 :
navigator.camera.getPicture (onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
}) ;
function onSuccess(imageData) {var image = document.getElementById('myImage') ;
image.src = "données : image / jpeg ; base64," + imageData;}
function onFail(message) {alert (' a échoué car: "+ message);}
Prendre une photo et récupérer l'emplacement du fichier de l'image :
navigator.camera.getPicture (onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI }) ;
function onSuccess(imageURI) {var image = document.getElementById('myImage') ;
image.SRC = imageURI ;
} function onFail(message) {alert (' a échoué car: "+ message);}
## CameraOptions
Paramètres optionnels pour personnaliser les réglages de l'appareil.
{qualité : destinationType 75,: Camera.DestinationType.DATA_URL, TypeSource : Camera.PictureSourceType.CAMERA, allowEdit : encodingType vrai,: Camera.EncodingType.JPEG, targetWidth : 100, targetHeight : 100, popoverOptions : CameraPopoverOptions, saveToPhotoAlbum : false} ;
### Options
* **qualité**: qualité de l'image enregistrée, exprimée en une gamme de 0 à 100, 100 étant généralement pleine résolution sans perte de compression de fichiers. La valeur par défaut est 50. *(Nombre)* (Notez que les informations sur la résolution de la caméra sont indisponibles).
* **destinationType**: choisissez le format de la valeur de retour. La valeur par défaut est FILE_URI. Définies dans `navigator.camera.DestinationType` *(nombre)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: définissez la source de l'image. La valeur par défaut est la caméra. Définies dans `navigator.camera.PictureSourceType` *(nombre)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: permettre un montage simple d'image avant la sélection. *(Booléen)*
* **encodingType**: choisir le fichier image retournée de codage. Valeur par défaut est JPEG. Définies dans `navigator.camera.EncodingType` *(nombre)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: largeur en pixels de l'image de l'échelle. Doit être utilisé avec **targetHeight**. Aspect ratio reste constant. *(Nombre)*
* **targetHeight**: hauteur en pixels de l'image de l'échelle. Doit être utilisé avec **targetWidth**. Aspect ratio reste constant. *(Nombre)*
* **mediaType**: définir le type de média pour choisir de. Ne fonctionne que quand `PictureSourceType` est `PHOTOLIBRARY` ou `SAVEDPHOTOALBUM` . Définies dans `nagivator.camera.MediaType` *(nombre)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. PAR DÉFAUT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: faire pivoter l'image afin de corriger l'orientation de l'appareil lors de la capture. *(Booléen)*
* **saveToPhotoAlbum**: enregistrer l'image sur l'album photo sur l'appareil après la capture. *(Booléen)*
* **popoverOptions**: iOS uniquement des options qui spécifient l'emplacement de kangourou dans iPad. Défini dans`CameraPopoverOptions`.
* **cameraDirection**: choisissez la caméra à utiliser (ou dos-face). La valeur par défaut est de retour. Définies dans `navigator.camera.Direction` *(nombre)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### Amazon Fire OS Quirks
* Tout `cameraDirection` résultats dans le back-face photo de valeur.
* Ignore la `allowEdit` paramètre.
* `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo.
### Quirks Android
* Tout `cameraDirection` résultats dans le back-face photo de valeur.
* Ignore la `allowEdit` paramètre.
* `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo.
### BlackBerry 10 Quirks
* Ignore la `quality` paramètre.
* Ignore la `allowEdit` paramètre.
* `Camera.MediaType`n'est pas pris en charge.
* Ignore la `correctOrientation` paramètre.
* Ignore la `cameraDirection` paramètre.
### Firefox OS Quirks
* Ignore la `quality` paramètre.
* `Camera.DestinationType`est ignorée et est égal à `1` (URI du fichier image)
* Ignore la `allowEdit` paramètre.
* Ignore la `PictureSourceType` paramètre (utilisateur il choisit dans une fenêtre de dialogue)
* Ignore le`encodingType`
* Ignore la `targetWidth` et`targetHeight`
* `Camera.MediaType`n'est pas pris en charge.
* Ignore la `correctOrientation` paramètre.
* Ignore la `cameraDirection` paramètre.
### iOS Quirks
* La valeur `quality` inférieur à 50 pour éviter les erreurs de mémoire sur certains appareils.
* Lorsque vous utilisez `destinationType.FILE_URI` , les photos sont sauvegardées dans le répertoire temporaire de l'application. Le contenu du répertoire temporaire de l'application est supprimé lorsque l'application se termine.
### Bizarreries de paciarelli
* options non prises en charge
* retourne toujours un URI de fichier
### Windows Phone 7 et 8 Quirks
* Ignore la `allowEdit` paramètre.
* Ignore la `correctOrientation` paramètre.
* Ignore la `cameraDirection` paramètre.
* Ignore la `saveToPhotoAlbum` paramètre. IMPORTANT : Toutes les images prises avec la caméra de cordova wp7/8 API sont toujours copiés au rôle d'appareil photo du téléphone. Selon les paramètres de l'utilisateur, cela pourrait également signifier que l'image est auto-téléchargées à leur OneDrive. Potentiellement, cela pourrait signifier que l'image est disponible à un public plus large que votre application destinée. Si ce un bloqueur pour votre application, vous devrez implémenter le CameraCaptureTask tel que documenté sur msdn : <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> vous pouvez aussi commenter ou haut-vote la question connexe dans le [gestionnaire d'incidents][3]
* Ignore la `mediaType` propriété de `cameraOptions` comme le kit de développement Windows Phone ne fournit pas un moyen de choisir les vidéos de PHOTOLIBRARY.
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
fonction de rappel onError qui fournit un message d'erreur.
function(message) {/ / afficher un message utile}
### Paramètres
* **message**: le message est fourni par du code natif de l'appareil. *(String)*
## cameraSuccess
fonction de rappel onSuccess qui fournit les données d'image.
function(ImageData) {/ / faire quelque chose avec l'image}
### Paramètres
* **imageData**: codage Base64 de l'image, *ou* le fichier image URI, selon `cameraOptions` en vigueur. *(String)*
### Exemple
Afficher image / / function cameraCallback(imageData) {var image = document.getElementById('myImage') ;
image.src = "données : image / jpeg ; base64," + imageData;}
## CameraPopoverHandle
Un handle vers la boîte de dialogue de kangourou créé par`navigator.camera.getPicture`.
### Méthodes
* **setPosition**: définir la position de la kangourou.
### Plates-formes prises en charge
* iOS
### setPosition
Définir la position de la kangourou.
**Paramètres**:
* `cameraPopoverOptions`: la `CameraPopoverOptions` qui spécifie la nouvelle position
### Exemple
var cameraPopoverHandle = navigator.camera.getPicture (onSuccess, onFail, {destinationType : Camera.DestinationType.FILE_URI, TypeSource : Camera.PictureSourceType.PHOTOLIBRARY, popoverOptions : nouvelle CameraPopoverOptions (300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)}) ;
Repositionner le kangourou si l'orientation change.
Window.onorientationchange = function() {var cameraPopoverOptions = new CameraPopoverOptions (0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY) ;
cameraPopoverHandle.setPosition(cameraPopoverOptions) ;
}
## CameraPopoverOptions
iOS uniquement les paramètres qui spécifient la direction ancre élément emplacement et de la flèche de la kangourou lors de la sélection des images de la bibliothèque de l'iPad ou l'album.
{x: 0, y: 32, largeur : 320, hauteur : 480, arrowDir : Camera.PopoverArrowDirection.ARROW_ANY} ;
### CameraPopoverOptions
* **x**: coordonnée de pixel de l'élément de l'écran sur lequel ancrer le kangourou x. *(Nombre)*
* **y**: coordonnée de y pixels de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
* **largeur**: largeur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
* **hauteur**: hauteur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
* **arrowDir**: Direction de la flèche sur le kangourou doit pointer. Définies dans `Camera.PopoverArrowDirection` *(nombre)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Notez que la taille de la kangourou peut changer pour s'adapter à la direction de la flèche et l'orientation de l'écran. Assurez-vous que tenir compte des changements d'orientation lors de la spécification de l'emplacement d'élément d'ancrage.
## Navigator.Camera.Cleanup
Supprime les intermédiaires photos prises par la caméra de stockage temporaire.
Navigator.Camera.Cleanup (cameraSuccess, cameraError) ;
### Description
Supprime les intermédiaires les fichiers image qui sont gardées en dépôt temporaire après avoir appelé `camera.getPicture` . S'applique uniquement lorsque la valeur de `Camera.sourceType` est égale à `Camera.PictureSourceType.CAMERA` et le `Camera.destinationType` est égal à`Camera.DestinationType.FILE_URI`.
### Plates-formes prises en charge
* iOS
### Exemple
Navigator.Camera.Cleanup (onSuccess, onFail) ;
fonction onSuccess() {console.log ("succès de caméra nettoyage.")}
function onFail(message) {alert (' a échoué car: "+ message);}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 753 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 716 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1009 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 984 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 806 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 776 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 802 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 770 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 965 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 936 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 573 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 550 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 649 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 622 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 784 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 759 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 714 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 679 B

View File

@@ -1,421 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
Questo plugin definisce un oggetto globale `navigator.camera`, che fornisce un'API per scattare foto e per aver scelto immagini dalla libreria di immagini del sistema.
Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## Installazione
cordova plugin add cordova-plugin-camera
## API
* Fotocamera
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* navigator.camera.cleanup
## navigator.camera.getPicture
Prende una foto utilizzando la fotocamera, o recupera una foto dalla galleria di immagini del dispositivo. L'immagine è passata al callback di successo come `String` con codifica base64, o come l'URI per il file di immagine. Lo stesso metodo restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare il Muffin di selezione file.
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### Descrizione
La funzione `camera.getPicture` apre predefinito fotocamera applicazione il dispositivo che consente agli utenti di scattare foto. Questo comportamento si verifica per impostazione predefinita, quando `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA`. Una volta che l'utente scatta la foto, si chiude l'applicazione fotocamera e l'applicazione viene ripristinato.
Se `Camera.sourceType` è `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM`, una finestra di dialogo Visualizza che permette agli utenti di selezionare un'immagine esistente. La funzione `camera.getPicture` restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare la finestra di selezione immagine, ad esempio, quando l'orientamento del dispositivo.
Il valore restituito viene inviato alla funzione di callback `cameraSuccess`, in uno dei seguenti formati, a seconda il `cameraOptions` specificato:
* A `String` contenente l'immagine della foto con codifica base64.
* A `String` che rappresenta il percorso del file di immagine su archiviazione locale (predefinito).
Si può fare quello che vuoi con l'immagine codificata o URI, ad esempio:
* Il rendering dell'immagine in un `<img>` tag, come nell'esempio qui sotto
* Salvare i dati localmente ( `LocalStorage` , [Lawnchair](http://brianleroux.github.com/lawnchair/), ecc.)
* Inviare i dati a un server remoto
**Nota**: risoluzione foto sui più recenti dispositivi è abbastanza buona. Foto selezionate dalla galleria del dispositivo non è percepiranno di qualità inferiore, anche se viene specificato un parametro di `quality`. Per evitare problemi di memoria comune, impostare `Camera.destinationType` `FILE_URI` piuttosto che `DATA_URL`.
#### Piattaforme supportate
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### Esempio
Scattare una foto e recuperarla come un'immagine con codifica base64:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Scattare una foto e recuperare il percorso del file dell'immagine:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### Preferenze (iOS)
* **CameraUsesGeolocation** (boolean, default è false). Per l'acquisizione di immagini JPEG, impostato su true per ottenere dati di geolocalizzazione nell'intestazione EXIF. Questo innescherà una richiesta per le autorizzazioni di geolocalizzazione, se impostato su true.
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon fuoco OS stranezze
Amazon fuoco OS utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di cordova.
#### Stranezze Android
Android utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di Cordova.
#### Stranezze browser
Può restituire solo la foto come immagine con codifica base64.
#### Firefox OS stranezze
Fotocamera plugin è attualmente implementato mediante [Web Activities](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
#### iOS stranezze
Compreso un JavaScript `alert()` in una delle funzioni di callback può causare problemi. Avvolgere l'avviso all'interno di un `setTimeout()` per consentire la selezione immagine iOS o muffin per chiudere completamente la prima che viene visualizzato l'avviso:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 capricci
Richiamando l'applicazione nativa fotocamera mentre il dispositivo è collegato tramite Zune non funziona e innesca un callback di errore.
#### Tizen stranezze
Tizen supporta solo a `destinationType` di `Camera.DestinationType.FILE_URI` e un `sourceType` di `Camera.PictureSourceType.PHOTOLIBRARY`.
## CameraOptions
Parametri opzionali per personalizzare le impostazioni della fotocamera.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
* **quality**: qualità dell'immagine salvata, espressa come un intervallo di 0-100, dove 100 è tipicamente piena risoluzione senza perdita di compressione file. Il valore predefinito è 50. *(Numero)* (Si noti che informazioni sulla risoluzione della fotocamera non sono disponibile).
* **destinationType**: Scegli il formato del valore restituito. Il valore predefinito è FILE_URI. Definito in `navigator.camera.DestinationType` *(numero)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: impostare l'origine dell'immagine. Il valore predefinito è la fotocamera. Definito in `navigator.camera.PictureSourceType` *(numero)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **Proprietà allowEdit**: consentire la semplice modifica dell'immagine prima di selezione. *(Booleano)*
* **encodingType**: scegliere il file immagine restituita di codifica. Predefinito è JPEG. Definito in `navigator.camera.EncodingType` *(numero)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: larghezza in pixel all'immagine della scala. Deve essere usato con **targetHeight**. Proporzioni rimane costante. *(Numero)*
* **targetHeight**: altezza in pixel all'immagine della scala. Deve essere usato con **targetWidth**. Proporzioni rimane costante. *(Numero)*
* **mediaType**: impostare il tipo di supporto per scegliere da. Funziona solo quando `PictureSourceType` è `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definito in `nagivator.camera.MediaType` *(numero)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. PER IMPOSTAZIONE PREDEFINITA. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: ruotare l'immagine per correggere l'orientamento del dispositivo durante l'acquisizione. *(Booleano)*
* **saveToPhotoAlbum**: salvare l'immagine nell'album di foto sul dispositivo dopo la cattura. *(Booleano)*
* **popoverOptions**: solo iOS opzioni che specificano la posizione di muffin in iPad. Definito in`CameraPopoverOptions`.
* **cameraDirection**: scegliere la telecamera da utilizzare (o retro-frontale). Il valore predefinito è tornato. Definito in `navigator.camera.Direction` *(numero)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### Amazon fuoco OS stranezze
* Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura.
* Ignora il `allowEdit` parametro.
* `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso.
#### Stranezze Android
* Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura.
* Android utilizza anche l'attività di ritaglio per allowEdit, anche se raccolto dovrebbe funzionare ed effettivamente passare l'immagine ritagliata a Cordova, l'unico che funziona è sempre quello in bundle con l'applicazione di Google Plus foto. Altre colture potrebbero non funzionare.
* `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso.
#### BlackBerry 10 capricci
* Ignora il `quality` parametro.
* Ignora il `allowEdit` parametro.
* `Camera.MediaType`non è supportato.
* Ignora il `correctOrientation` parametro.
* Ignora il `cameraDirection` parametro.
#### Firefox OS stranezze
* Ignora il `quality` parametro.
* `Camera.DestinationType`viene ignorato e corrisponde a `1` (URI del file di immagine)
* Ignora il `allowEdit` parametro.
* Ignora il `PictureSourceType` parametro (utente ne sceglie in una finestra di dialogo)
* Ignora il`encodingType`
* Ignora le `targetWidth` e`targetHeight`
* `Camera.MediaType`non è supportato.
* Ignora il `correctOrientation` parametro.
* Ignora il `cameraDirection` parametro.
#### iOS stranezze
* Impostare `quality` inferiore al 50 per evitare errori di memoria su alcuni dispositivi.
* Quando si utilizza `destinationType.FILE_URI` , foto vengono salvati nella directory temporanea dell'applicazione. Il contenuto della directory temporanea dell'applicazione viene eliminato quando l'applicazione termina.
#### Tizen stranezze
* opzioni non supportate
* restituisce sempre un URI del FILE
#### Windows Phone 7 e 8 stranezze
* Ignora il `allowEdit` parametro.
* Ignora il `correctOrientation` parametro.
* Ignora il `cameraDirection` parametro.
* Ignora il `saveToPhotoAlbum` parametro. IMPORTANTE: Tutte le immagini scattate con la fotocamera di cordova wp7/8 API vengono sempre copiate rotolo fotocamera del telefono cellulare. A seconda delle impostazioni dell'utente, questo potrebbe anche significare che l'immagine viene caricato in automatico a loro OneDrive. Questo potenzialmente potrebbe significare che l'immagine è disponibile a un pubblico più ampio di app destinate. Se questo un blocco dell'applicazione, sarà necessario implementare il CameraCaptureTask come documentato su msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> si può anche commentare o up-voto la questione correlata nel [tracciatore di problemi](https://issues.apache.org/jira/browse/CB-2083)
* Ignora la `mediaType` proprietà di `cameraOptions` come il SDK di Windows Phone non fornisce un modo per scegliere il video da PHOTOLIBRARY.
## CameraError
funzione di callback onError che fornisce un messaggio di errore.
function(message) {
// Show a helpful message
}
#### Descrizione
* **message**: il messaggio è fornito dal codice nativo del dispositivo. *(String)*
## cameraSuccess
funzione di callback onSuccess che fornisce i dati di immagine.
function(imageData) {
// Do something with the image
}
#### Descrizione
* **imageData**: Base64 codifica dei dati immagine, *o* il file di immagine URI, a seconda `cameraOptions` in vigore. *(String)*
#### Esempio
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Un handle per la finestra di dialogo di muffin creato da `navigator.camera.getPicture`.
#### Descrizione
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### Piattaforme supportate
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Esempio
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS solo parametri che specificano l'ancoraggio elemento posizione e freccia direzione il Muffin quando si selezionano le immagini dalla libreria un iPad o un album.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### Descrizione
* **x**: pixel coordinata x dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **y**: coordinata y di pixel dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **width**: larghezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **height**: altezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **arrowDir**: direzione dovrebbe puntare la freccia il muffin. Definito in `Camera.PopoverArrowDirection` *(numero)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Si noti che la dimensione del muffin possa cambiare per regolare la direzione della freccia e l'orientamento dello schermo. Assicurarsi che tenere conto di modifiche di orientamento quando si specifica la posizione di elemento di ancoraggio.
## navigator.camera.cleanup
Rimuove intermedio foto scattate con la fotocamera da deposito temporaneo.
navigator.camera.cleanup( cameraSuccess, cameraError );
#### Descrizione
Rimuove i file di immagine intermedia che vengono tenuti in custodia temporanea dopo la chiamata a `camera.getPicture`. Si applica solo quando il valore di `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA` e il `Camera.destinationType` è uguale a `Camera.DestinationType.FILE_URI`.
#### Piattaforme supportate
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Esempio
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,434 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
Questo plugin definisce un oggetto globale `navigator.camera`, che fornisce un'API per scattare foto e per aver scelto immagini dalla libreria di immagini del sistema.
Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## Installazione
cordova plugin add cordova-plugin-camera
## navigator.camera.getPicture
Prende una foto utilizzando la fotocamera, o recupera una foto dalla galleria di immagini del dispositivo. L'immagine è passata al callback di successo come `String` con codifica base64, o come l'URI per il file di immagine. Lo stesso metodo restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare il Muffin di selezione file.
navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions );
### Descrizione
La funzione `camera.getPicture` apre predefinito fotocamera applicazione il dispositivo che consente agli utenti di scattare foto. Questo comportamento si verifica per impostazione predefinita, quando `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA`. Una volta che l'utente scatta la foto, si chiude l'applicazione fotocamera e l'applicazione viene ripristinato.
Se `Camera.sourceType` è `Camera.PictureSourceType.PHOTOLIBRARY` o `Camera.PictureSourceType.SAVEDPHOTOALBUM`, una finestra di dialogo Visualizza che permette agli utenti di selezionare un'immagine esistente. La funzione `camera.getPicture` restituisce un oggetto `CameraPopoverHandle` che può essere utilizzato per riposizionare la finestra di selezione immagine, ad esempio, quando l'orientamento del dispositivo.
Il valore restituito viene inviato alla funzione di callback `cameraSuccess`, in uno dei seguenti formati, a seconda il `cameraOptions` specificato:
* A `String` contenente l'immagine della foto con codifica base64.
* A `String` che rappresenta il percorso del file di immagine su archiviazione locale (predefinito).
Si può fare quello che vuoi con l'immagine codificata o URI, ad esempio:
* Il rendering dell'immagine in un `<img>` tag, come nell'esempio qui sotto
* Salvare i dati localmente ( `LocalStorage` , [Lawnchair][1], ecc.)
* Inviare i dati a un server remoto
[1]: http://brianleroux.github.com/lawnchair/
**Nota**: risoluzione foto sui più recenti dispositivi è abbastanza buona. Foto selezionate dalla galleria del dispositivo non è percepiranno di qualità inferiore, anche se viene specificato un parametro di `quality`. Per evitare problemi di memoria comune, impostare `Camera.destinationType` `FILE_URI` piuttosto che `DATA_URL`.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Browser
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Preferenze (iOS)
* **CameraUsesGeolocation** (boolean, default è false). Per l'acquisizione di immagini JPEG, impostato su true per ottenere dati di geolocalizzazione nell'intestazione EXIF. Questo innescherà una richiesta per le autorizzazioni di geolocalizzazione, se impostato su true.
<preference name="CameraUsesGeolocation" value="false" />
### Amazon fuoco OS stranezze
Amazon fuoco OS utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di cordova.
### Stranezze Android
Android utilizza intenti a lanciare l'attività della fotocamera sul dispositivo per catturare immagini e sui telefoni con poca memoria, l'attività di Cordova può essere ucciso. In questo scenario, l'immagine potrebbe non apparire quando viene ripristinata l'attività di Cordova.
### Stranezze browser
Può restituire solo la foto come immagine con codifica base64.
### Firefox OS stranezze
Fotocamera plugin è attualmente implementato mediante [Web Activities][2].
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### iOS stranezze
Compreso un JavaScript `alert()` in una delle funzioni di callback può causare problemi. Avvolgere l'avviso all'interno di un `setTimeout()` per consentire la selezione immagine iOS o muffin per chiudere completamente la prima che viene visualizzato l'avviso:
setTimeout(function() {
// do your thing here!
}, 0);
### Windows Phone 7 stranezze
Richiamando l'applicazione nativa fotocamera mentre il dispositivo è collegato tramite Zune non funziona e innesca un callback di errore.
### Tizen stranezze
Tizen supporta solo a `destinationType` di `Camera.DestinationType.FILE_URI` e un `sourceType` di `Camera.PictureSourceType.PHOTOLIBRARY`.
### Esempio
Scattare una foto e recuperarla come un'immagine con codifica base64:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Scattare una foto e recuperare il percorso del file dell'immagine:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
## CameraOptions
Parametri opzionali per personalizzare le impostazioni della fotocamera.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
### Opzioni
* **quality**: qualità dell'immagine salvata, espressa come un intervallo di 0-100, dove 100 è tipicamente piena risoluzione senza perdita di compressione file. Il valore predefinito è 50. *(Numero)* (Si noti che informazioni sulla risoluzione della fotocamera non sono disponibile).
* **destinationType**: Scegli il formato del valore restituito. Il valore predefinito è FILE_URI. Definito in `navigator.camera.DestinationType` *(numero)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: impostare l'origine dell'immagine. Il valore predefinito è la fotocamera. Definito in `navigator.camera.PictureSourceType` *(numero)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **Proprietà allowEdit**: consentire la semplice modifica dell'immagine prima di selezione. *(Booleano)*
* **encodingType**: scegliere il file immagine restituita di codifica. Predefinito è JPEG. Definito in `navigator.camera.EncodingType` *(numero)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: larghezza in pixel all'immagine della scala. Deve essere usato con **targetHeight**. Proporzioni rimane costante. *(Numero)*
* **targetHeight**: altezza in pixel all'immagine della scala. Deve essere usato con **targetWidth**. Proporzioni rimane costante. *(Numero)*
* **mediaType**: impostare il tipo di supporto per scegliere da. Funziona solo quando `PictureSourceType` è `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definito in `nagivator.camera.MediaType` *(numero)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. PER IMPOSTAZIONE PREDEFINITA. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: ruotare l'immagine per correggere l'orientamento del dispositivo durante l'acquisizione. *(Booleano)*
* **saveToPhotoAlbum**: salvare l'immagine nell'album di foto sul dispositivo dopo la cattura. *(Booleano)*
* **popoverOptions**: solo iOS opzioni che specificano la posizione di muffin in iPad. Definito in`CameraPopoverOptions`.
* **cameraDirection**: scegliere la telecamera da utilizzare (o retro-frontale). Il valore predefinito è tornato. Definito in `navigator.camera.Direction` *(numero)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### Amazon fuoco OS stranezze
* Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura.
* Ignora il `allowEdit` parametro.
* `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso.
### Stranezze Android
* Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura.
* Ignora il `allowEdit` parametro.
* `Camera.PictureSourceType.PHOTOLIBRARY`e `Camera.PictureSourceType.SAVEDPHOTOALBUM` entrambi visualizzare l'album fotografico stesso.
### BlackBerry 10 capricci
* Ignora il `quality` parametro.
* Ignora il `allowEdit` parametro.
* `Camera.MediaType`non è supportato.
* Ignora il `correctOrientation` parametro.
* Ignora il `cameraDirection` parametro.
### Firefox OS stranezze
* Ignora il `quality` parametro.
* `Camera.DestinationType`viene ignorato e corrisponde a `1` (URI del file di immagine)
* Ignora il `allowEdit` parametro.
* Ignora il `PictureSourceType` parametro (utente ne sceglie in una finestra di dialogo)
* Ignora il`encodingType`
* Ignora le `targetWidth` e`targetHeight`
* `Camera.MediaType`non è supportato.
* Ignora il `correctOrientation` parametro.
* Ignora il `cameraDirection` parametro.
### iOS stranezze
* Impostare `quality` inferiore al 50 per evitare errori di memoria su alcuni dispositivi.
* Quando si utilizza `destinationType.FILE_URI` , foto vengono salvati nella directory temporanea dell'applicazione. Il contenuto della directory temporanea dell'applicazione viene eliminato quando l'applicazione termina.
### Tizen stranezze
* opzioni non supportate
* restituisce sempre un URI del FILE
### Windows Phone 7 e 8 stranezze
* Ignora il `allowEdit` parametro.
* Ignora il `correctOrientation` parametro.
* Ignora il `cameraDirection` parametro.
* Ignora il `saveToPhotoAlbum` parametro. IMPORTANTE: Tutte le immagini scattate con la fotocamera di cordova wp7/8 API vengono sempre copiate rotolo fotocamera del telefono cellulare. A seconda delle impostazioni dell'utente, questo potrebbe anche significare che l'immagine viene caricato in automatico a loro OneDrive. Questo potenzialmente potrebbe significare che l'immagine è disponibile a un pubblico più ampio di app destinate. Se questo un blocco dell'applicazione, sarà necessario implementare il CameraCaptureTask come documentato su msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> si può anche commentare o up-voto la questione correlata nel [tracciatore di problemi][3]
* Ignora la `mediaType` proprietà di `cameraOptions` come il SDK di Windows Phone non fornisce un modo per scegliere il video da PHOTOLIBRARY.
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
funzione di callback onError che fornisce un messaggio di errore.
function(message) {
// Show a helpful message
}
### Parametri
* **message**: il messaggio è fornito dal codice nativo del dispositivo. *(String)*
## cameraSuccess
funzione di callback onSuccess che fornisce i dati di immagine.
function(imageData) {
// Do something with the image
}
### Parametri
* **imageData**: Base64 codifica dei dati immagine, *o* il file di immagine URI, a seconda `cameraOptions` in vigore. *(String)*
### Esempio
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Un handle per la finestra di dialogo di muffin creato da `navigator.camera.getPicture`.
### Metodi
* **setPosition**: impostare la posizione dei muffin.
### Piattaforme supportate
* iOS
### setPosition
Impostare la posizione dei muffin.
**Parametri**:
* `cameraPopoverOptions`: il `CameraPopoverOptions` che specificare la nuova posizione
### Esempio
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS solo parametri che specificano l'ancoraggio elemento posizione e freccia direzione il Muffin quando si selezionano le immagini dalla libreria un iPad o un album.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
### CameraPopoverOptions
* **x**: pixel coordinata x dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **y**: coordinata y di pixel dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **width**: larghezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **height**: altezza, in pixel, dell'elemento dello schermo su cui ancorare il muffin. *(Numero)*
* **arrowDir**: direzione dovrebbe puntare la freccia il muffin. Definito in `Camera.PopoverArrowDirection` *(numero)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Si noti che la dimensione del muffin possa cambiare per regolare la direzione della freccia e l'orientamento dello schermo. Assicurarsi che tenere conto di modifiche di orientamento quando si specifica la posizione di elemento di ancoraggio.
## navigator.camera.cleanup
Rimuove intermedio foto scattate con la fotocamera da deposito temporaneo.
navigator.camera.cleanup( cameraSuccess, cameraError );
### Descrizione
Rimuove i file di immagine intermedia che vengono tenuti in custodia temporanea dopo la chiamata a `camera.getPicture`. Si applica solo quando il valore di `Camera.sourceType` è uguale a `Camera.PictureSourceType.CAMERA` e il `Camera.destinationType` è uguale a `Camera.DestinationType.FILE_URI`.
### Piattaforme supportate
* iOS
### Esempio
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,421 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
このプラグインは、写真を撮るため、システムのイメージ ライブラリからイメージを選択するために API を提供します、グローバル `navigator.camera` オブジェクトを定義します。
オブジェクトは、グローバル スコープの `ナビゲーター` に添付、それがないまで `deviceready` イベントの後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## インストール
cordova plugin add cordova-plugin-camera
## API
* カメラ
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* navigator.camera.cleanup
## navigator.camera.getPicture
カメラを使用して写真を取るか、デバイスの画像ギャラリーから写真を取得します。 イメージが渡されます成功時のコールバックを base64 エンコードされた `文字列`、または、URI としてイメージ ファイル。 メソッド自体はファイル選択ポップ オーバーの位置を変更するために使用できる `CameraPopoverHandle` オブジェクトを返します。
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### 解説
`camera.getPicture` 関数は、ユーザーの写真をスナップすることができますデバイスのデフォルト カメラ アプリケーションを開きます。 `Camera.sourceType``Camera.PictureSourceType.CAMERA` と等しい場合既定では、この現象が発生します。 ユーザーは写真をスナップ、カメラ アプリケーションを閉じるし、アプリケーションが復元されます。
`Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` または `Camera.PictureSourceType.SAVEDPHOTOALBUM` の場合、ダイアログ ボックスはユーザーを既存のイメージを選択することができますが表示されます。 `camera.getPicture` 関数は、デバイスの向きが変更されたとき、たとえば、イメージの選択ダイアログには、位置を変更するために使用することができます、`CameraPopoverHandle` オブジェクトを返します。
戻り値が `cameraSuccess` コールバック関数の指定 `cameraOptions` に応じて、次の形式のいずれかに送信されます。
* A `String` 写真の base64 でエンコードされたイメージを含んでいます。
* A `String` (既定値) のローカル記憶域上のイメージ ファイルの場所を表します。
自由に変更、エンコードされたイメージ、または URI などを行うことができます。
* イメージをレンダリングする `<img>` 以下の例のように、タグ
* ローカル データの保存 ( `LocalStorage` 、 [Lawnchair](http://brianleroux.github.com/lawnchair/)など)。
* リモート サーバーにデータを投稿します。
**注**: 新しいデバイス上の写真の解像度はかなり良いです。 デバイスのギャラリーから選択した写真は `quality` パラメーターが指定されて場合でも下方の品質に縮小されません。 一般的なメモリの問題を避けるために `DATA_URL` ではなく `FILE_URI``Camera.destinationType` を設定します。.
#### サポートされているプラットフォーム
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### 例
写真を撮るし、base64 エンコード イメージとして取得します。
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
写真を撮るし、イメージのファイルの場所を取得します。
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### 環境設定 iOS
* **CameraUsesGeolocation**(ブール値、デフォルトは false)。 Jpeg 画像をキャプチャするため EXIF ヘッダーで地理位置情報データを取得する場合は true に設定します。 これは、場合地理位置情報のアクセス許可に対する要求をトリガーする true に設定します。
<preference name="CameraUsesGeolocation" value="false" />
#### アマゾン火 OS 癖
アマゾン火 OS イメージをキャプチャするデバイス上のカメラの活動を開始する意図を使用して、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。
#### Android の癖
アンドロイド、イメージをキャプチャするデバイス上でカメラのアクティビティを開始する意図を使用し、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。
#### ブラウザーの癖
Base64 エンコード イメージとして写真を返すのみことができます。
#### Firefox OS 癖
カメラのプラグインは現在、[Web アクティビティ](https://hacks.mozilla.org/2013/01/introducing-web-activities/) を使用して実装されていた.
#### iOS の癖
コールバック関数のいずれかの JavaScript `alert()` を含む問題が発生することができます。 IOS イメージ ピッカーまたは完全が終了するまで、警告が表示されますポップ オーバーを許可する `setTimeout()` 内でアラートをラップします。
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 の癖
ネイティブ カメラ アプリケーションを呼び出すと、デバイスが Zune を介して接続されている動作しませんし、エラー コールバックをトリガーします。
#### Tizen の癖
Tizen のみ `Camera.DestinationType.FILE_URI``destinationType``Camera.PictureSourceType.PHOTOLIBRARY``sourceType` をサポートしています.
## CameraOptions
カメラの設定をカスタマイズするオプションのパラメーター。
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
* **quality** 0-100、100 がファイルの圧縮から損失なしで通常のフル解像度の範囲で表される、保存されたイメージの品質。 既定値は 50 です。 *(数)*(カメラの解像度についての情報が利用できないことに注意してください)。
* **destinationType**: 戻り値の形式を選択します。既定値は FILE_URI です。定義されている `navigator.camera.DestinationType` *(番号)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: 画像のソースを設定します。既定値は、カメラです。定義されている `navigator.camera.PictureSourceType` *(番号)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: 単純な選択の前に画像の編集を許可します。*(ブール値)*
* **encodingType**: 返されるイメージ ファイルのエンコーディングを選択します。デフォルトは JPEG です。定義されている `navigator.camera.EncodingType` *(番号)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: スケール イメージにピクセル単位の幅。**TargetHeight**を使用する必要があります。縦横比は変わりません。*(数)*
* **targetHeight**: スケール イメージにピクセル単位の高さ。**TargetWidth**を使用する必要があります。縦横比は変わりません。*(数)*
* **mediaType** から選択するメディアの種類を設定します。 場合にのみ働きます `PictureSourceType``PHOTOLIBRARY` または `SAVEDPHOTOALBUM` 。 定義されている `nagivator.camera.MediaType` *(番号)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: キャプチャ中に、デバイスの向きを修正する画像を回転させます。*(ブール値)*
* **saveToPhotoAlbum**: キャプチャ後、デバイス上のフォト アルバムに画像を保存します。*(ブール値)*
* **popoverOptions**: iPad のポップ オーバーの場所を指定する iOS のみのオプションです。定義されています。`CameraPopoverOptions`.
* **cameraDirection** (前面または背面側) を使用するカメラを選択します。既定値は戻るです。定義されている `navigator.camera.Direction` *(番号)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### アマゾン火 OS 癖
* 任意 `cameraDirection` 背面写真で結果の値します。
* 無視、 `allowEdit` パラメーター。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。
#### Android の癖
* 任意 `cameraDirection` 背面写真で結果の値します。
* アンドロイドも使用しています作物活性、allowEdit もトリミングする必要があります動作し、実際にトリミングされた画像をコルドバで 1 つだけの作品一貫して Google プラス写真アプリケーションにバンドルされているものであることに渡します。 他の作物が機能しません。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。
#### ブラックベリー 10 癖
* 無視、 `quality` パラメーター。
* 無視、 `allowEdit` パラメーター。
* `Camera.MediaType`サポートされていません。
* 無視、 `correctOrientation` パラメーター。
* 無視、 `cameraDirection` パラメーター。
#### Firefox OS 癖
* 無視、 `quality` パラメーター。
* `Camera.DestinationType`無視され、等しい `1` (イメージ ファイル URI)
* 無視、 `allowEdit` パラメーター。
* 無視、 `PictureSourceType` パラメーター (ユーザーが選択ダイアログ ウィンドウに)
* 無視します、`encodingType`
* 無視、 `targetWidth``targetHeight`
* `Camera.MediaType`サポートされていません。
* 無視、 `correctOrientation` パラメーター。
* 無視、 `cameraDirection` パラメーター。
#### iOS の癖
* 設定 `quality` 一部のデバイスでメモリ不足エラーを避けるために 50 の下。
* 使用する場合 `destinationType.FILE_URI` 、写真、アプリケーションの一時ディレクトリに保存されます。アプリケーションの一時ディレクトリの内容は、アプリケーションの終了時に削除されます。
#### Tizen の癖
* サポートされていないオプション
* 常にファイルの URI を返す
#### Windows Phone 7 と 8 癖
* 無視、 `allowEdit` パラメーター。
* 無視、 `correctOrientation` パラメーター。
* 無視、 `cameraDirection` パラメーター。
* 無視、 `saveToPhotoAlbum` パラメーター。 重要: wp7/8 コルドバ カメラ API で撮影したすべての画像は携帯電話のカメラ巻き物に常にコピーします。 ユーザーの設定に応じて、これも、画像はその OneDrive に自動アップロードを意味できます。 イメージは意図したアプリより広い聴衆に利用できる可能性があります可能性があります。 場合は、このアプリケーションのブロッカー、msdn で説明されているように、CameraCaptureTask を実装する必要があります: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx>コメントにすることがありますもかアップ投票関連の問題を[課題追跡システム](https://issues.apache.org/jira/browse/CB-2083)で
* 無視、 `mediaType` のプロパティ `cameraOptions` として Windows Phone SDK には、フォト ライブラリからビデオを選択する方法は行いません。
## CameraError
エラー メッセージを提供する onError コールバック関数。
function(message) {
// Show a helpful message
}
#### 解説
* **message**: メッセージは、デバイスのネイティブ コードによって提供されます。*(文字列)*
## cameraSuccess
画像データを提供する onSuccess コールバック関数。
function(imageData) {
// Do something with the image
}
#### 解説
* **imagedata を扱う**: Base64 エンコード イメージのデータ、*または*画像ファイルによって URI の `cameraOptions` 効果。*(文字列)*
#### 例
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
`Navigator.camera.getPicture` によって作成されたポップオーバーパン ダイアログ ボックスへのハンドル.
#### 解説
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### サポートされているプラットフォーム
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### 例
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS だけ指定パラメーターをポップ オーバーのアンカー要素の場所および矢印方向計算されたライブラリまたはアルバムから画像を選択するとき。
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### 解説
* **x**: ピクセルの x 座標画面要素にポップ オーバーのアンカーになります。*(数)*
* **y**: y ピクセル座標の画面要素にポップ オーバーのアンカーになります。*(数)*
* **width**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の幅。*(数)*
* **height**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の高さ。*(数)*
* **arrowDir**: 方向のポップ オーバーで矢印をポイントする必要があります。定義されている `Camera.PopoverArrowDirection` *(番号)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
矢印の方向と、画面の向きを調整するポップ オーバーのサイズを変更可能性がありますに注意してください。 アンカー要素の位置を指定するときの方向の変化を考慮することを確認します。
## navigator.camera.cleanup
削除中間一時ストレージからカメラで撮影した写真。
navigator.camera.cleanup( cameraSuccess, cameraError );
#### 解説
`camera.getPicture` を呼び出した後一時記憶域に保存されている中間画像ファイルを削除します。 `Camera.sourceType` の値が `Camera.PictureSourceType.CAMERA` に等しい、`Camera.destinationType``Camera.DestinationType.FILE_URI` と等しいの場合にのみ適用されます。.
#### サポートされているプラットフォーム
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### 例
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,434 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
このプラグインは、写真を撮るため、システムのイメージ ライブラリからイメージを選択するために API を提供します、グローバル `navigator.camera` オブジェクトを定義します。
オブジェクトは、グローバル スコープの `ナビゲーター` に添付、それがないまで `deviceready` イベントの後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## インストール
cordova plugin add cordova-plugin-camera
## navigator.camera.getPicture
カメラを使用して写真を取るか、デバイスの画像ギャラリーから写真を取得します。 イメージが渡されます成功時のコールバックを base64 エンコードされた `文字列`、または、URI としてイメージ ファイル。 メソッド自体はファイル選択ポップ オーバーの位置を変更するために使用できる `CameraPopoverHandle` オブジェクトを返します。
navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions );
### 解説
`camera.getPicture` 関数は、ユーザーの写真をスナップすることができますデバイスのデフォルト カメラ アプリケーションを開きます。 `Camera.sourceType``Camera.PictureSourceType.CAMERA` と等しい場合既定では、この現象が発生します。 ユーザーは写真をスナップ、カメラ アプリケーションを閉じるし、アプリケーションが復元されます。
`Camera.sourceType` `Camera.PictureSourceType.PHOTOLIBRARY` または `Camera.PictureSourceType.SAVEDPHOTOALBUM` の場合、ダイアログ ボックスはユーザーを既存のイメージを選択することができますが表示されます。 `camera.getPicture` 関数は、デバイスの向きが変更されたとき、たとえば、イメージの選択ダイアログには、位置を変更するために使用することができます、`CameraPopoverHandle` オブジェクトを返します。
戻り値が `cameraSuccess` コールバック関数の指定 `cameraOptions` に応じて、次の形式のいずれかに送信されます。
* A `String` 写真の base64 でエンコードされたイメージを含んでいます。
* A `String` (既定値) のローカル記憶域上のイメージ ファイルの場所を表します。
自由に変更、エンコードされたイメージ、または URI などを行うことができます。
* イメージをレンダリングする `<img>` 以下の例のように、タグ
* ローカル データの保存 ( `LocalStorage` 、 [Lawnchair][1]など)。
* リモート サーバーにデータを投稿します。
[1]: http://brianleroux.github.com/lawnchair/
**注**: 新しいデバイス上の写真の解像度はかなり良いです。 デバイスのギャラリーから選択した写真は `quality` パラメーターが指定されて場合でも下方の品質に縮小されません。 一般的なメモリの問題を避けるために `DATA_URL` ではなく `FILE_URI``Camera.destinationType` を設定します。.
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* ブラウザー
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 環境設定 iOS
* **CameraUsesGeolocation**(ブール値、デフォルトは false)。 Jpeg 画像をキャプチャするため EXIF ヘッダーで地理位置情報データを取得する場合は true に設定します。 これは、場合地理位置情報のアクセス許可に対する要求をトリガーする true に設定します。
<preference name="CameraUsesGeolocation" value="false" />
### アマゾン火 OS 癖
アマゾン火 OS イメージをキャプチャするデバイス上のカメラの活動を開始する意図を使用して、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。
### Android の癖
アンドロイド、イメージをキャプチャするデバイス上でカメラのアクティビティを開始する意図を使用し、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。
### ブラウザーの癖
Base64 エンコード イメージとして写真を返すのみことができます。
### Firefox OS 癖
カメラのプラグインは現在、[Web アクティビティ][2] を使用して実装されていた.
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### iOS の癖
コールバック関数のいずれかの JavaScript `alert()` を含む問題が発生することができます。 IOS イメージ ピッカーまたは完全が終了するまで、警告が表示されますポップ オーバーを許可する `setTimeout()` 内でアラートをラップします。
setTimeout(function() {
// do your thing here!
}, 0);
### Windows Phone 7 の癖
ネイティブ カメラ アプリケーションを呼び出すと、デバイスが Zune を介して接続されている動作しませんし、エラー コールバックをトリガーします。
### Tizen の癖
Tizen のみ `Camera.DestinationType.FILE_URI``destinationType``Camera.PictureSourceType.PHOTOLIBRARY``sourceType` をサポートしています.
### 例
写真を撮るし、base64 エンコード イメージとして取得します。
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
写真を撮るし、イメージのファイルの場所を取得します。
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
## CameraOptions
カメラの設定をカスタマイズするオプションのパラメーター。
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
### オプション
* **quality** 0-100、100 がファイルの圧縮から損失なしで通常のフル解像度の範囲で表される、保存されたイメージの品質。 既定値は 50 です。 *(数)*(カメラの解像度についての情報が利用できないことに注意してください)。
* **destinationType**: 戻り値の形式を選択します。既定値は FILE_URI です。定義されている `navigator.camera.DestinationType` *(番号)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: 画像のソースを設定します。既定値は、カメラです。定義されている `navigator.camera.PictureSourceType` *(番号)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: 単純な選択の前に画像の編集を許可します。*(ブール値)*
* **encodingType**: 返されるイメージ ファイルのエンコーディングを選択します。デフォルトは JPEG です。定義されている `navigator.camera.EncodingType` *(番号)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: スケール イメージにピクセル単位の幅。**TargetHeight**を使用する必要があります。縦横比は変わりません。*(数)*
* **targetHeight**: スケール イメージにピクセル単位の高さ。**TargetWidth**を使用する必要があります。縦横比は変わりません。*(数)*
* **mediaType** から選択するメディアの種類を設定します。 場合にのみ働きます `PictureSourceType``PHOTOLIBRARY` または `SAVEDPHOTOALBUM` 。 定義されている `nagivator.camera.MediaType` *(番号)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: キャプチャ中に、デバイスの向きを修正する画像を回転させます。*(ブール値)*
* **saveToPhotoAlbum**: キャプチャ後、デバイス上のフォト アルバムに画像を保存します。*(ブール値)*
* **popoverOptions**: iPad のポップ オーバーの場所を指定する iOS のみのオプションです。定義されています。`CameraPopoverOptions`.
* **cameraDirection** (前面または背面側) を使用するカメラを選択します。既定値は戻るです。定義されている `navigator.camera.Direction` *(番号)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### アマゾン火 OS 癖
* 任意 `cameraDirection` 背面写真で結果の値します。
* 無視、 `allowEdit` パラメーター。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。
### Android の癖
* 任意 `cameraDirection` 背面写真で結果の値します。
* 無視、 `allowEdit` パラメーター。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`両方のアルバムが表示されます同じ写真。
### ブラックベリー 10 癖
* 無視、 `quality` パラメーター。
* 無視、 `allowEdit` パラメーター。
* `Camera.MediaType`サポートされていません。
* 無視、 `correctOrientation` パラメーター。
* 無視、 `cameraDirection` パラメーター。
### Firefox OS 癖
* 無視、 `quality` パラメーター。
* `Camera.DestinationType`無視され、等しい `1` (イメージ ファイル URI)
* 無視、 `allowEdit` パラメーター。
* 無視、 `PictureSourceType` パラメーター (ユーザーが選択ダイアログ ウィンドウに)
* 無視します、`encodingType`
* 無視、 `targetWidth``targetHeight`
* `Camera.MediaType`サポートされていません。
* 無視、 `correctOrientation` パラメーター。
* 無視、 `cameraDirection` パラメーター。
### iOS の癖
* 設定 `quality` 一部のデバイスでメモリ不足エラーを避けるために 50 の下。
* 使用する場合 `destinationType.FILE_URI` 、写真、アプリケーションの一時ディレクトリに保存されます。アプリケーションの一時ディレクトリの内容は、アプリケーションの終了時に削除されます。
### Tizen の癖
* サポートされていないオプション
* 常にファイルの URI を返す
### Windows Phone 7 と 8 癖
* 無視、 `allowEdit` パラメーター。
* 無視、 `correctOrientation` パラメーター。
* 無視、 `cameraDirection` パラメーター。
* 無視、 `saveToPhotoAlbum` パラメーター。 重要: wp7/8 コルドバ カメラ API で撮影したすべての画像は携帯電話のカメラ巻き物に常にコピーします。 ユーザーの設定に応じて、これも、画像はその OneDrive に自動アップロードを意味できます。 イメージは意図したアプリより広い聴衆に利用できる可能性があります可能性があります。 場合は、このアプリケーションのブロッカー、msdn で説明されているように、CameraCaptureTask を実装する必要があります: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx>コメントにすることがありますもかアップ投票関連の問題を[課題追跡システム][3]で
* 無視、 `mediaType` のプロパティ `cameraOptions` として Windows Phone SDK には、フォト ライブラリからビデオを選択する方法は行いません。
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
エラー メッセージを提供する onError コールバック関数。
function(message) {
// Show a helpful message
}
### パラメーター
* **message**: メッセージは、デバイスのネイティブ コードによって提供されます。*(文字列)*
## cameraSuccess
画像データを提供する onSuccess コールバック関数。
function(imageData) {
// Do something with the image
}
### パラメーター
* **imagedata を扱う**: Base64 エンコード イメージのデータ、*または*画像ファイルによって URI の `cameraOptions` 効果。*(文字列)*
### 例
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
`Navigator.camera.getPicture` によって作成されたポップオーバーパン ダイアログ ボックスへのハンドル.
### メソッド
* **setPosition**: ポップ オーバーの位置を設定します。
### サポートされているプラットフォーム
* iOS
### setPosition
ポップ オーバーの位置を設定します。
**パラメーター**:
* `cameraPopoverOptions`:、 `CameraPopoverOptions` の新しい位置を指定します。
### 例
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS だけ指定パラメーターをポップ オーバーのアンカー要素の場所および矢印方向計算されたライブラリまたはアルバムから画像を選択するとき。
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
### CameraPopoverOptions
* **x**: ピクセルの x 座標画面要素にポップ オーバーのアンカーになります。*(数)*
* **y**: y ピクセル座標の画面要素にポップ オーバーのアンカーになります。*(数)*
* **width**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の幅。*(数)*
* **height**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の高さ。*(数)*
* **arrowDir**: 方向のポップ オーバーで矢印をポイントする必要があります。定義されている `Camera.PopoverArrowDirection` *(番号)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
矢印の方向と、画面の向きを調整するポップ オーバーのサイズを変更可能性がありますに注意してください。 アンカー要素の位置を指定するときの方向の変化を考慮することを確認します。
## navigator.camera.cleanup
削除中間一時ストレージからカメラで撮影した写真。
navigator.camera.cleanup( cameraSuccess, cameraError );
### 説明
`camera.getPicture` を呼び出した後一時記憶域に保存されている中間画像ファイルを削除します。 `Camera.sourceType` の値が `Camera.PictureSourceType.CAMERA` に等しい、`Camera.destinationType``Camera.DestinationType.FILE_URI` と等しいの場合にのみ適用されます。.
### サポートされているプラットフォーム
* iOS
### 例
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,421 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
이 플러그인 시스템의 이미지 라이브러리에서 이미지를 선택 및 사진 촬영을 위한 API를 제공 하는 글로벌 `navigator.camera` 개체를 정의 합니다.
개체 `navigator` 글로벌 범위 첨부 아니에요 때까지 사용할 수 있는 `deviceready` 이벤트 후.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## 설치
cordova plugin add cordova-plugin-camera
## API
* 카메라
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* navigator.camera.cleanup
## navigator.camera.getPicture
카메라를 사용 하 여 사진을 걸립니다 또는 소자의 이미지 갤러리에서 사진을 검색 합니다. 이미지는 성공 콜백에 전달 base64 인코딩된 `문자열` 또는 URI로 이미지 파일에 대 한. 방법 자체는 파일 선택 popover 위치를 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다.
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### 설명
`Camera.getPicture` 함수 스냅 사진을 사용자가 소자의 기본 카메라 응용 프로그램을 엽니다. 이 문제는 `Camera.sourceType` `Camera.PictureSourceType.CAMERA` 경우 기본적으로 발생 합니다. 일단 사용자 스냅 사진, 카메라 응용 프로그램 종료 하 고 응용 프로그램 복원 됩니다.
`Camera.sourceType``Camera.PictureSourceType.PHOTOLIBRARY` 또는 `Camera.PictureSourceType.SAVEDPHOTOALBUM`, 대화 상자가 사용자가 기존 이미지를 선택할 수 있도록 표시 됩니다. `camera.getPicture` 함수는 장치 방향 변경 될 때 이미지 선택 대화 상자, 예를 들어, 위치를 변경 하려면 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다.
반환 값은 `cameraSuccess` 콜백 함수 지정된 `cameraOptions`에 따라 다음 형식 중 하나에 전송 됩니다.
* A `String` base64 인코딩된 사진 이미지를 포함 합니다.
* A `String` 로컬 저장소 (기본값)의 이미지 파일 위치를 나타내는.
할 수 있는 당신이 원하는대로 인코딩된 이미지 또는 URI, 예를 들면:
* 렌더링 이미지는 `<img>` 아래 예제와 같이 태그
* 로컬로 데이터를 저장 ( `LocalStorage` , [Lawnchair](http://brianleroux.github.com/lawnchair/), 등.)
* 원격 서버에 데이터 게시
**참고**: 더 새로운 장치에 사진 해상도 아주 좋은. 소자의 갤러리에서 선택 된 사진 `품질` 매개 변수를 지정 하는 경우에 낮은 품질에 관하여 하지는. 일반적인 메모리 문제를 피하기 위해 `DATA_URL` 보다 `FILE_URI` `Camera.destinationType` 설정.
#### 지원 되는 플랫폼
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### 예를 들어
촬영 및 base64 인코딩 이미지로 검색:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
촬영 하 고 이미지의 파일 위치를 검색:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### 환경 설정 (iOS)
* **CameraUsesGeolocation** (boolean, 기본값: false)입니다. 캡처 Jpeg, EXIF 헤더에 지리적 데이터를 true로 설정 합니다. 이 경우 위치 정보 사용 권한에 대 한 요청을 일으킬 것 이다 true로 설정 합니다.
<preference name="CameraUsesGeolocation" value="false" />
#### 아마존 화재 OS 단점
아마존 화재 OS 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다.
#### 안 드 로이드 단점
안 드 로이드 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다.
#### 브라우저 만지면
수 base64 인코딩 이미지로 사진을 반환 합니다.
#### 파이어 폭스 OS 단점
카메라 플러그인은 현재 [웹 활동](https://hacks.mozilla.org/2013/01/introducing-web-activities/)를 사용 하 여 구현.
#### iOS 단점
자바 `alert()`를 포함 하 여 콜백 함수 중 하나에 문제가 발생할 수 있습니다. 포장 허용 iOS 이미지 피커 또는 popover를 완벽 하 게 경고를 표시 하기 전에 닫습니다 `setTimeout()` 내에서 경고:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 단점
장치 Zune 통해 연결 된 동안 네이티브 카메라 응용 프로그램을 호출 하면 작동 하지 않습니다 하 고 오류 콜백 트리거합니다.
#### Tizen 특수
`Camera.DestinationType.FILE_URI``destinationType``Camera.PictureSourceType.PHOTOLIBRARY``sourceType` Tizen 지원.
## CameraOptions
카메라 설정을 사용자 지정 하는 선택적 매개 변수.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
* **품질**: 범위 0-100, 100은 파일 압축에서 손실 없이 일반적으로 전체 해상도 저장된 된 이미지의 품질. 기본값은 50입니다. *(수)* (Note 카메라의 해상도 대 한 정보는 사용할 수 없습니다.)
* **destinationType**: 반환 값의 형식을 선택 합니다. 기본값은 FILE_URI입니다. 에 정의 된 `navigator.camera.DestinationType` *(수)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: 그림의 소스를 설정 합니다. 기본값은 카메라입니다. 에 정의 된 `navigator.camera.PictureSourceType` *(수)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: 선택 하기 전에 이미지의 간단한 편집을 허용 합니다. *(부울)*
* **encodingType**: 반환 된 이미지 파일의 인코딩을 선택 합니다. 기본값은 JPEG입니다. 에 정의 된 `navigator.camera.EncodingType` *(수)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: 스케일 이미지를 픽셀 너비. **TargetHeight**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)*
* **targetHeight**: 스케일 이미지를 픽셀 단위로 높이. **TargetWidth**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)*
* **mediaType**:에서 선택 미디어 유형을 설정 합니다. 때에 작동 `PictureSourceType``PHOTOLIBRARY` 또는 `SAVEDPHOTOALBUM` . 에 정의 된 `nagivator.camera.MediaType` *(수)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. 기본입니다. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: 캡처 도중 장치의 방향에 대 한 해결 하기 위해 이미지를 회전 합니다. *(부울)*
* **saveToPhotoAlbum**: 캡처 후 장치에서 사진 앨범에 이미지를 저장 합니다. *(부울)*
* **popoverOptions**: iPad에 popover 위치를 지정 하는 iOS 전용 옵션. 에 정의 된`CameraPopoverOptions`.
* **cameraDirection**: (앞 이나 뒤로-연결)를 사용 하 여 카메라를 선택 하십시오. 기본값은 다시. 에 정의 된 `navigator.camera.Direction` *(수)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### 아마존 화재 OS 단점
* 어떤 `cameraDirection` 다시 연결 사진에 결과 값.
* 무시는 `allowEdit` 매개 변수.
* `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다.
#### 안 드 로이드 단점
* 어떤 `cameraDirection` 다시 연결 사진에 결과 값.
* 안 드 로이드도 사용 자르기 활동 allowEdit, 비록 작물 작업과 실제로 코르도바, 유일 하 게 작품 지속적으로 구글 플러스 사진 응용 프로그램과 함께 번들로 제공 하는 것은 등을 맞댄 자른된 이미지를 전달 해야 합니다. 다른 작물은 작동 하지 않을 수 있습니다.
* `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다.
#### 블랙베리 10 단점
* 무시는 `quality` 매개 변수.
* 무시는 `allowEdit` 매개 변수.
* `Camera.MediaType`지원 되지 않습니다.
* 무시는 `correctOrientation` 매개 변수.
* 무시는 `cameraDirection` 매개 변수.
#### 파이어 폭스 OS 단점
* 무시는 `quality` 매개 변수.
* `Camera.DestinationType`무시 되 고 `1` (이미지 파일 URI)
* 무시는 `allowEdit` 매개 변수.
* 무시는 `PictureSourceType` 매개 변수 (사용자가 선택 그것 대화 창에서)
* 무시 하는`encodingType`
* 무시는 `targetWidth``targetHeight`
* `Camera.MediaType`지원 되지 않습니다.
* 무시는 `correctOrientation` 매개 변수.
* 무시는 `cameraDirection` 매개 변수.
#### iOS 단점
* 설정 `quality` 일부 장치 메모리 오류를 피하기 위해 50 아래.
* 사용 하는 경우 `destinationType.FILE_URI` , 사진 응용 프로그램의 임시 디렉터리에 저장 됩니다. 응용 프로그램이 종료 될 때 응용 프로그램의 임시 디렉터리의 내용은 삭제 됩니다.
#### Tizen 특수
* 지원 되지 않는 옵션
* 항상 파일 URI를 반환 합니다.
#### Windows Phone 7, 8 특수
* 무시는 `allowEdit` 매개 변수.
* 무시는 `correctOrientation` 매개 변수.
* 무시는 `cameraDirection` 매개 변수.
* 무시는 `saveToPhotoAlbum` 매개 변수. 중요: 모든 이미지 API wp7/8 코르도바 카메라로 촬영 항상 복사 됩니다 휴대 전화의 카메라 롤에. 사용자의 설정에 따라이 또한 그들의 OneDrive에 자동 업로드 이미지는 의미. 이 잠재적으로 이미지는 당신의 애플 리 케이 션을 위한 보다 넓은 청중에 게 사용할 수 있는 의미. 이 경우 응용 프로그램에 대 한 차단, 당신은 msdn에 설명 대로 단말기를 구현 해야 합니다: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> 수 있습니다 또한 의견 또는 [이슈 트래커](https://issues.apache.org/jira/browse/CB-2083) 에서 업-투표 관련된 문제
* 무시는 `mediaType` 속성을 `cameraOptions` 으로 Windows Phone SDK PHOTOLIBRARY에서 비디오를 선택 하는 방법을 제공 하지 않습니다.
## CameraError
오류 메시지를 제공 하는 onError 콜백 함수.
function(message) {
// Show a helpful message
}
#### 설명
* **메시지**: 메시지는 장치의 네이티브 코드에 의해 제공 됩니다. *(문자열)*
## cameraSuccess
이미지 데이터를 제공 하는 onSuccess 콜백 함수.
function(imageData) {
// Do something with the image
}
#### 설명
* **imageData**: Base64 인코딩은 이미지 데이터, *또는* 이미지 파일에 따라 URI의 `cameraOptions` 적용. *(문자열)*
#### 예를 들어
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
`navigator.camera.getPicture`에 의해 만들어진 popover 대화에 대 한 핸들.
#### 설명
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### 지원 되는 플랫폼
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### 예를 들어
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS 전용 매개 변수 iPad의 보관 함 또는 앨범에서 이미지를 선택 하면 앵커 요소 위치와 화살표의 방향으로 popover 지정 하는.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### 설명
* **x**: x는 popover 앵커는 화면 요소의 픽셀 좌표. *(수)*
* **y**: y 픽셀 좌표는 popover 앵커는 화면 요소입니다. *(수)*
* **폭**: 폭 (픽셀)는 popover 앵커는 화면 요소. *(수)*
* **높이**: 높이 (픽셀)는 popover 앵커는 화면 요소. *(수)*
* **arrowDir**: 방향 화살표는 popover 가리켜야 합니다. 에 정의 된 `Camera.PopoverArrowDirection` *(수)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
참고는 popover의 크기 조정 화살표 방향 및 화면 방향 변경 될 수 있습니다. 앵커 요소 위치를 지정 하는 경우 방향 변경에 대 한 계정에 있는지 확인 합니다.
## navigator.camera.cleanup
제거 임시 저장소에서 카메라로 찍은 사진을 중간.
navigator.camera.cleanup( cameraSuccess, cameraError );
#### 설명
`camera.getPicture`를 호출한 후 임시 저장소에 보관 됩니다 중간 이미지 파일을 제거 합니다. `Camera.sourceType` 값은 `Camera.PictureSourceType.CAMERA``Camera.destinationType``Camera.DestinationType.FILE_URI` 때만 적용 됩니다..
#### 지원 되는 플랫폼
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### 예를 들어
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,434 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
이 플러그인 시스템의 이미지 라이브러리에서 이미지를 선택 및 사진 촬영을 위한 API를 제공 하는 글로벌 `navigator.camera` 개체를 정의 합니다.
개체 `navigator` 글로벌 범위 첨부 아니에요 때까지 사용할 수 있는 `deviceready` 이벤트 후.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## 설치
cordova plugin add cordova-plugin-camera
## navigator.camera.getPicture
카메라를 사용 하 여 사진을 걸립니다 또는 소자의 이미지 갤러리에서 사진을 검색 합니다. 이미지는 성공 콜백에 전달 base64 인코딩된 `문자열` 또는 URI로 이미지 파일에 대 한. 방법 자체는 파일 선택 popover 위치를 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다.
navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions );
### 설명
`Camera.getPicture` 함수 스냅 사진을 사용자가 소자의 기본 카메라 응용 프로그램을 엽니다. 이 문제는 `Camera.sourceType` `Camera.PictureSourceType.CAMERA` 경우 기본적으로 발생 합니다. 일단 사용자 스냅 사진, 카메라 응용 프로그램 종료 하 고 응용 프로그램 복원 됩니다.
`Camera.sourceType``Camera.PictureSourceType.PHOTOLIBRARY` 또는 `Camera.PictureSourceType.SAVEDPHOTOALBUM`, 대화 상자가 사용자가 기존 이미지를 선택할 수 있도록 표시 됩니다. `camera.getPicture` 함수는 장치 방향 변경 될 때 이미지 선택 대화 상자, 예를 들어, 위치를 변경 하려면 사용할 수 있는 `CameraPopoverHandle` 개체를 반환 합니다.
반환 값은 `cameraSuccess` 콜백 함수 지정된 `cameraOptions`에 따라 다음 형식 중 하나에 전송 됩니다.
* A `String` base64 인코딩된 사진 이미지를 포함 합니다.
* A `String` 로컬 저장소 (기본값)의 이미지 파일 위치를 나타내는.
할 수 있는 당신이 원하는대로 인코딩된 이미지 또는 URI, 예를 들면:
* 렌더링 이미지는 `<img>` 아래 예제와 같이 태그
* 로컬로 데이터를 저장 ( `LocalStorage` , [Lawnchair][1], 등.)
* 원격 서버에 데이터 게시
[1]: http://brianleroux.github.com/lawnchair/
**참고**: 더 새로운 장치에 사진 해상도 아주 좋은. 소자의 갤러리에서 선택 된 사진 `품질` 매개 변수를 지정 하는 경우에 낮은 품질에 관하여 하지는. 일반적인 메모리 문제를 피하기 위해 `DATA_URL` 보다 `FILE_URI` `Camera.destinationType` 설정.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* 브라우저
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 환경 설정 (iOS)
* **CameraUsesGeolocation** (boolean, 기본값: false)입니다. 캡처 Jpeg, EXIF 헤더에 지리적 데이터를 true로 설정 합니다. 이 경우 위치 정보 사용 권한에 대 한 요청을 일으킬 것 이다 true로 설정 합니다.
<preference name="CameraUsesGeolocation" value="false" />
### 아마존 화재 OS 단점
아마존 화재 OS 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다.
### 안 드 로이드 단점
안 드 로이드 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다.
### 브라우저 만지면
수 base64 인코딩 이미지로 사진을 반환 합니다.
### 파이어 폭스 OS 단점
카메라 플러그인은 현재 [웹 활동][2]를 사용 하 여 구현.
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### iOS 단점
자바 `alert()`를 포함 하 여 콜백 함수 중 하나에 문제가 발생할 수 있습니다. 포장 허용 iOS 이미지 피커 또는 popover를 완벽 하 게 경고를 표시 하기 전에 닫습니다 `setTimeout()` 내에서 경고:
setTimeout(function() {
// do your thing here!
}, 0);
### Windows Phone 7 단점
장치 Zune 통해 연결 된 동안 네이티브 카메라 응용 프로그램을 호출 하면 작동 하지 않습니다 하 고 오류 콜백 트리거합니다.
### Tizen 특수
`Camera.DestinationType.FILE_URI``destinationType``Camera.PictureSourceType.PHOTOLIBRARY``sourceType` Tizen 지원.
### 예를 들어
촬영 및 base64 인코딩 이미지로 검색:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
촬영 하 고 이미지의 파일 위치를 검색:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
## CameraOptions
카메라 설정을 사용자 지정 하는 선택적 매개 변수.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
### 옵션
* **품질**: 범위 0-100, 100은 파일 압축에서 손실 없이 일반적으로 전체 해상도 저장된 된 이미지의 품질. 기본값은 50입니다. *(수)* (Note 카메라의 해상도 대 한 정보는 사용할 수 없습니다.)
* **destinationType**: 반환 값의 형식을 선택 합니다. 기본값은 FILE_URI입니다. 에 정의 된 `navigator.camera.DestinationType` *(수)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: 그림의 소스를 설정 합니다. 기본값은 카메라입니다. 에 정의 된 `navigator.camera.PictureSourceType` *(수)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: 선택 하기 전에 이미지의 간단한 편집을 허용 합니다. *(부울)*
* **encodingType**: 반환 된 이미지 파일의 인코딩을 선택 합니다. 기본값은 JPEG입니다. 에 정의 된 `navigator.camera.EncodingType` *(수)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: 스케일 이미지를 픽셀 너비. **TargetHeight**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)*
* **targetHeight**: 스케일 이미지를 픽셀 단위로 높이. **TargetWidth**와 함께 사용 해야 합니다. 가로 세로 비율이 일정 하 게 유지 합니다. *(수)*
* **mediaType**:에서 선택 미디어 유형을 설정 합니다. 때에 작동 `PictureSourceType``PHOTOLIBRARY` 또는 `SAVEDPHOTOALBUM` . 에 정의 된 `nagivator.camera.MediaType` *(수)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. 기본입니다. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: 캡처 도중 장치의 방향에 대 한 해결 하기 위해 이미지를 회전 합니다. *(부울)*
* **saveToPhotoAlbum**: 캡처 후 장치에서 사진 앨범에 이미지를 저장 합니다. *(부울)*
* **popoverOptions**: iPad에 popover 위치를 지정 하는 iOS 전용 옵션. 에 정의 된`CameraPopoverOptions`.
* **cameraDirection**: (앞 이나 뒤로-연결)를 사용 하 여 카메라를 선택 하십시오. 기본값은 다시. 에 정의 된 `navigator.camera.Direction` *(수)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### 아마존 화재 OS 단점
* 어떤 `cameraDirection` 다시 연결 사진에 결과 값.
* 무시는 `allowEdit` 매개 변수.
* `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다.
### 안 드 로이드 단점
* 어떤 `cameraDirection` 다시 연결 사진에 결과 값.
* 무시는 `allowEdit` 매개 변수.
* `Camera.PictureSourceType.PHOTOLIBRARY`그리고 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 둘 다 동일한 사진 앨범을 표시 합니다.
### 블랙베리 10 단점
* 무시는 `quality` 매개 변수.
* 무시는 `allowEdit` 매개 변수.
* `Camera.MediaType`지원 되지 않습니다.
* 무시는 `correctOrientation` 매개 변수.
* 무시는 `cameraDirection` 매개 변수.
### 파이어 폭스 OS 단점
* 무시는 `quality` 매개 변수.
* `Camera.DestinationType`무시 되 고 `1` (이미지 파일 URI)
* 무시는 `allowEdit` 매개 변수.
* 무시는 `PictureSourceType` 매개 변수 (사용자가 선택 그것 대화 창에서)
* 무시 하는`encodingType`
* 무시는 `targetWidth``targetHeight`
* `Camera.MediaType`지원 되지 않습니다.
* 무시는 `correctOrientation` 매개 변수.
* 무시는 `cameraDirection` 매개 변수.
### iOS 단점
* 설정 `quality` 일부 장치 메모리 오류를 피하기 위해 50 아래.
* 사용 하는 경우 `destinationType.FILE_URI` , 사진 응용 프로그램의 임시 디렉터리에 저장 됩니다. 응용 프로그램이 종료 될 때 응용 프로그램의 임시 디렉터리의 내용은 삭제 됩니다.
### Tizen 특수
* 지원 되지 않는 옵션
* 항상 파일 URI를 반환 합니다.
### Windows Phone 7, 8 특수
* 무시는 `allowEdit` 매개 변수.
* 무시는 `correctOrientation` 매개 변수.
* 무시는 `cameraDirection` 매개 변수.
* 무시는 `saveToPhotoAlbum` 매개 변수. 중요: 모든 이미지 API wp7/8 코르도바 카메라로 촬영 항상 복사 됩니다 휴대 전화의 카메라 롤에. 사용자의 설정에 따라이 또한 그들의 OneDrive에 자동 업로드 이미지는 의미. 이 잠재적으로 이미지는 당신의 애플 리 케이 션을 위한 보다 넓은 청중에 게 사용할 수 있는 의미. 이 경우 응용 프로그램에 대 한 차단, 당신은 msdn에 설명 대로 단말기를 구현 해야 합니다: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> 수 있습니다 또한 의견 또는 [이슈 트래커][3] 에서 업-투표 관련된 문제
* 무시는 `mediaType` 속성을 `cameraOptions` 으로 Windows Phone SDK PHOTOLIBRARY에서 비디오를 선택 하는 방법을 제공 하지 않습니다.
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
오류 메시지를 제공 하는 onError 콜백 함수.
function(message) {
// Show a helpful message
}
### 매개 변수
* **메시지**: 메시지는 장치의 네이티브 코드에 의해 제공 됩니다. *(문자열)*
## cameraSuccess
이미지 데이터를 제공 하는 onSuccess 콜백 함수.
function(imageData) {
// Do something with the image
}
### 매개 변수
* **imageData**: Base64 인코딩은 이미지 데이터, *또는* 이미지 파일에 따라 URI의 `cameraOptions` 적용. *(문자열)*
### 예를 들어
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
`navigator.camera.getPicture`에 의해 만들어진 popover 대화에 대 한 핸들.
### 메서드
* **setPosition**:는 popover의 위치를 설정 합니다.
### 지원 되는 플랫폼
* iOS
### setPosition
popover의 위치를 설정 합니다.
**매개 변수**:
* `cameraPopoverOptions`:는 `CameraPopoverOptions` 새 위치를 지정 하는
### 예를 들어
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS 전용 매개 변수 iPad의 보관 함 또는 앨범에서 이미지를 선택 하면 앵커 요소 위치와 화살표의 방향으로 popover 지정 하는.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
### CameraPopoverOptions
* **x**: x는 popover 앵커는 화면 요소의 픽셀 좌표. *(수)*
* **y**: y 픽셀 좌표는 popover 앵커는 화면 요소입니다. *(수)*
* **폭**: 폭 (픽셀)는 popover 앵커는 화면 요소. *(수)*
* **높이**: 높이 (픽셀)는 popover 앵커는 화면 요소. *(수)*
* **arrowDir**: 방향 화살표는 popover 가리켜야 합니다. 에 정의 된 `Camera.PopoverArrowDirection` *(수)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
참고는 popover의 크기 조정 화살표 방향 및 화면 방향 변경 될 수 있습니다. 앵커 요소 위치를 지정 하는 경우 방향 변경에 대 한 계정에 있는지 확인 합니다.
## navigator.camera.cleanup
제거 임시 저장소에서 카메라로 찍은 사진을 중간.
navigator.camera.cleanup( cameraSuccess, cameraError );
### 설명
`camera.getPicture`를 호출한 후 임시 저장소에 보관 됩니다 중간 이미지 파일을 제거 합니다. `Camera.sourceType` 값은 `Camera.PictureSourceType.CAMERA``Camera.destinationType``Camera.DestinationType.FILE_URI` 때만 적용 됩니다..
### 지원 되는 플랫폼
* iOS
### 예를 들어
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,421 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
Ten plugin definiuje obiekt globalny `navigator.camera`, który dostarcza API do robienia zdjęć i wybór zdjęć z biblioteki obrazów systemu.
Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostępne dopiero po zdarzeniu `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## Instalacja
cordova plugin add cordova-plugin-camera
## API
* Aparat
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* navigator.camera.cleanup
## navigator.camera.getPicture
Ma zdjęcia za pomocą aparatu, lub pobiera zdjęcia z urządzenia Galeria zdjęć. Obraz jest przekazywany do wywołania zwrotnego sukces jako kodowane algorytmem base64 `ciąg`, lub identyfikator URI dla pliku obrazu. Sama metoda zwraca obiekt `CameraPopoverHandle`, który może służyć do zmiany położenia pliku wyboru popover.
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### Opis
Funkcja `camera.getPicture` otwiera urządzenia domyślnej aplikacji aparat fotograficzny ów pozwala użytkownik wobec chwycić zębami kino. To zachowanie występuje domyślnie, gdy `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA`. Gdy użytkownik zaskoczy zdjęcie, ten aparat fotograficzny applicationâ zamyka i aplikacji jest przywracany.
Jeśli `Camera.sourceType` jest równe `Camera.PictureSourceType.PHOTOLIBRARY` lub `Camera.PictureSourceType.SAVEDPHOTOALBUM`, wtedy zostanie wyświetlone okno dialogowe pozwalające użytkownikowi na wybór istniejącego obrazu. Funkcja `camera.getPicture` zwraca obiekt `CameraPopoverHandle`, który obsługuje zmianę położenia okna wyboru obrazu, np. po zmianie orientacji urządzenia.
Zwracana wartość jest wysyłany do funkcji wywołania zwrotnego `cameraSuccess`, w jednym z następujących formatów, w zależności od określonego `cameraOptions`:
* `String` zawierający obraz zakodowany przy pomocy base64.
* `String` reprezentujący lokalizację pliku obrazu w lokalnym magazynie (domyślnie).
Może rób, co chcesz z zakodowany obraz lub identyfikatora URI, na przykład:
* Przedstawić obraz w tagu `<img>`, jak w przykładzie poniżej
* Zapisać lokalnie dane (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
* Wysłać dane na zdalny serwer
**Uwaga**: zdjęcie rozdzielczości na nowsze urządzenia jest bardzo dobry. Zdjęcia wybrane z galerii urządzenia są nie przeskalowanych w dół do niższej jakości, nawet jeśli określono parametr `quality`. Aby uniknąć typowych problemów z pamięci, zestaw `Camera.destinationType` `FILE_URI` zamiast `DATA_URL`.
#### Obsługiwane platformy
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### Przykład
Zrób zdjęcie i pobrać go jako kodowane algorytmem base64 obrazu:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Zrób zdjęcie i pobrać lokalizacji pliku obrazu:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### Preferencje (iOS)
* **CameraUsesGeolocation** (boolean, wartość domyślna to false). Do przechwytywania JPEG, zestaw do true, aby uzyskać danych geolokalizacyjnych w nagłówku EXIF. To spowoduje wniosek o geolokalizacji uprawnienia, jeśli zestaw na wartość true.
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon ogień OS dziwactwa
Amazon ogień OS używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności cordova.
#### Dziwactwa Androida
Android używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności Cordova.
#### Quirks przeglądarki
Może zwracać tylko zdjęcia jako obraz w formacie algorytmem base64.
#### Firefox OS dziwactwa
Aparat plugin jest obecnie implementowane za pomocą [Działania sieci Web](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
#### Dziwactwa iOS
W jednej z funkcji wywołania zwrotnego w tym JavaScript `alert()` może powodować problemy. Owinąć w `setTimeout()` umożliwia wybór obrazu iOS lub popover całkowicie zamknąć zanim wyświetli alert alert:
setTimeout(function() {
// do your thing here!
}, 0);
#### Dziwactwa Windows Phone 7
Wywoływanie aparat native aplikacji, podczas gdy urządzenie jest podłączone przez Zune nie działa i powoduje błąd wywołania zwrotnego.
#### Dziwactwa Tizen
Tizen obsługuje tylko `destinationType` z `Camera.DestinationType.FILE_URI` i `sourceType` z `Camera.PictureSourceType.PHOTOLIBRARY`.
## CameraOptions
Opcjonalne parametry, aby dostosować ustawienia aparatu.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
* **quality**: Jakość zapisywanego obrazu, wyrażona w przedziale 0-100, gdzie 100 zazwyczaj jest maksymalną rozdzielczością bez strat w czasie kompresji pliku. Wartością domyślną jest 50. *(Liczba)* (Pamiętaj, że informacja o rozdzielczości aparatu jest niedostępna.)
* **destinationType**: Wybierz format zwracanej wartości. Wartością domyślną jest FILE_URI. Zdefiniowane w `navigator.camera.DestinationType` *(numer)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: Ustaw źródło obrazu. Wartością domyślną jest aparat fotograficzny. Zdefiniowane w `navigator.camera.PictureSourceType` *(numer)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: Pozwala na prostą edycję obrazu przed zaznaczeniem. *(Boolean)*
* **encodingType**: Wybierz plik obrazu zwracany jest kodowanie. Domyślnie jest JPEG. Zdefiniowane w `navigator.camera.EncodingType` *(numer)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: Szerokość w pikselach skalowanego obrazu. Musi być użyte z **targetHeight**. Współczynnik proporcji pozostaje stały. *(Liczba)*
* **targetHeight**: Wysokość w pikselach skalowanego obrazu. Musi być użyte z **targetWidth**. Współczynnik proporcji pozostaje stały. *(Liczba)*
* **mediaType**: Ustawia typ nośnika, z którego będzie wybrany. Działa tylko wtedy, gdy `PictureSourceType` jest `PHOTOLIBRARY` lub `SAVEDPHOTOALBUM`. Zdefiniowane w `nagivator.camera.MediaType` *(Liczba)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: Obraca obraz aby skorygować orientację urządzenia podczas przechwytywania. *(Boolean)*
* **saveToPhotoAlbum**: Po przechwyceniu zapisuje na urządzeniu obraz w albumie na zdjęcia. *(Boolean)*
* **popoverOptions**: Opcja tylko dla platformy iOS, która określa położenie wyskakującego okna na iPadzie. Zdefiniowane w `CameraPopoverOptions`.
* **cameraDirection**: Wybierz aparat do korzystania (lub z powrotem przodem). Wartością domyślną jest z powrotem. Zdefiniowane w `navigator.camera.Direction` *(numer)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### Amazon ogień OS dziwactwa
* Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery.
* Parametr `allowEdit` jest ignorowany.
* Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami.
#### Dziwactwa Androida
* Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery.
* Android również używa aktywność upraw dla allowEdit, choć upraw powinien pracować i faktycznie przejść przycięte zdjęcie Wróć do Cordova, ten tylko jeden który działa konsekwentnie jest ten, wiązany z aplikacji Google Plus zdjęcia. Inne rośliny mogą nie działać.
* Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami.
#### Jeżyna 10 dziwactwa
* Parametr `quality` jest ignorowany.
* Parametr `allowEdit` jest ignorowany.
* Nie jest wspierane `Camera.MediaType`.
* Parametr `correctOrientation` jest ignorowany.
* Parametr `cameraDirection` jest ignorowany.
#### Firefox OS dziwactwa
* Parametr `quality` jest ignorowany.
* `Camera.DestinationType`jest ignorowane i jest równa `1` (plik obrazu URI)
* Parametr `allowEdit` jest ignorowany.
* Ignoruje `PictureSourceType` parametr (użytkownik wybiera go w oknie dialogowym)
* Ignoruje`encodingType`
* Ignoruje `targetWidth` i`targetHeight`
* Nie jest wspierane `Camera.MediaType`.
* Parametr `correctOrientation` jest ignorowany.
* Parametr `cameraDirection` jest ignorowany.
#### Dziwactwa iOS
* Ustaw `quality` poniżej 50 aby uniknąć błędów pamięci na niektórych urządzeniach.
* Podczas korzystania z `destinationType.FILE_URI` , zdjęcia są zapisywane w katalogu tymczasowego stosowania. Zawartość katalogu tymczasowego stosowania jest usuwany po zakończeniu aplikacji.
#### Dziwactwa Tizen
* opcje nie są obsługiwane
* zawsze zwraca FILE URI
#### Windows Phone 7 i 8 dziwactwa
* Parametr `allowEdit` jest ignorowany.
* Parametr `correctOrientation` jest ignorowany.
* Parametr `cameraDirection` jest ignorowany.
* Ignoruje `saveToPhotoAlbum` parametr. Ważne: Wszystkie zdjęcia zrobione aparatem wp7/8 cordova API są zawsze kopiowane do telefonu w kamerze. W zależności od ustawień użytkownika może to też oznaczać że obraz jest automatycznie przesłane do ich OneDrive. Potencjalnie może to oznaczać, że obraz jest dostępne dla szerszego grona odbiorców niż Twoja aplikacja przeznaczona. Jeśli ten bloker aplikacji, trzeba będzie wdrożenie CameraCaptureTask, opisane na msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> można także komentarz lub górę głosowanie powiązanych kwestii w [śledzenia błędów](https://issues.apache.org/jira/browse/CB-2083)
* Ignoruje `mediaType` Właściwość `cameraOptions` jako SDK Windows Phone nie umożliwiają wybór filmów z PHOTOLIBRARY.
## CameraError
funkcja wywołania zwrotnego PrzyBłędzie, która zawiera komunikat o błędzie.
function(message) {
// Show a helpful message
}
#### Opis
* **message**: Natywny kod komunikatu zapewniany przez urządzenie. *(Ciąg znaków)*
## cameraSuccess
onSuccess funkcji wywołania zwrotnego, który dostarcza dane obrazu.
function(imageData) {
// Do something with the image
}
#### Opis
* **imageData**: Dane obrazu kodowane przy pomocy Base64 *lub* URI pliku obrazu, w zależności od użycia `cameraOptions`. *(Ciąg znaków)*
#### Przykład
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Uchwyt do okna dialogowego popover, stworzony przez `navigator.camera.getPicture`.
#### Opis
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### Obsługiwane platformy
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Przykład
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
tylko do iOS parametrami, które określić kotwicy element lokalizacji i strzałka kierunku popover, przy wyborze zdjęć z iPad biblioteki lub album.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### Opis
* **x**: współrzędna piksela x elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **y**: współrzędna piksela y elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **width**: szerokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **height**: wysokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **arrowDir**: Kierunek, który powinna wskazywać strzałka na wyskakującym oknie. Zdefiniowane w `Camera.PopoverArrowDirection` *(Liczba)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Należy pamiętać, że rozmiar popover może zmienić aby zmienić kierunek strzałki i orientacji ekranu. Upewnij się uwzględnić zmiany orientacji podczas określania położenia elementu kotwicy.
## navigator.camera.cleanup
Usuwa pośrednie zdjęcia zrobione przez aparat z czasowego składowania.
navigator.camera.cleanup( cameraSuccess, cameraError );
#### Opis
Usuwa pliki obrazów pośrednich, które są przechowywane w pamięci tymczasowej po wywołaniu `camera.getPicture`. Ma zastosowanie tylko, gdy wartość `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA` i `Camera.destinationType` jest równa `Camera.DestinationType.FILE_URI`.
#### Obsługiwane platformy
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Przykład
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,434 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
Ten plugin definiuje obiekt globalny `navigator.camera`, który dostarcza API do robienia zdjęć i wybór zdjęć z biblioteki obrazów systemu.
Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostępne dopiero po zdarzeniu `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## Instalacja
cordova plugin add cordova-plugin-camera
## navigator.camera.getPicture
Ma zdjęcia za pomocą aparatu, lub pobiera zdjęcia z urządzenia Galeria zdjęć. Obraz jest przekazywany do wywołania zwrotnego sukces jako kodowane algorytmem base64 `ciąg`, lub identyfikator URI dla pliku obrazu. Sama metoda zwraca obiekt `CameraPopoverHandle`, który może służyć do zmiany położenia pliku wyboru popover.
navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions );
### Opis
Funkcja `camera.getPicture` otwiera urządzenia domyślnej aplikacji aparat fotograficzny ów pozwala użytkownik wobec chwycić zębami kino. To zachowanie występuje domyślnie, gdy `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA`. Gdy użytkownik zaskoczy zdjęcie, ten aparat fotograficzny applicationâ zamyka i aplikacji jest przywracany.
Jeśli `Camera.sourceType` jest równe `Camera.PictureSourceType.PHOTOLIBRARY` lub `Camera.PictureSourceType.SAVEDPHOTOALBUM`, wtedy zostanie wyświetlone okno dialogowe pozwalające użytkownikowi na wybór istniejącego obrazu. Funkcja `camera.getPicture` zwraca obiekt `CameraPopoverHandle`, który obsługuje zmianę położenia okna wyboru obrazu, np. po zmianie orientacji urządzenia.
Zwracana wartość jest wysyłany do funkcji wywołania zwrotnego `cameraSuccess`, w jednym z następujących formatów, w zależności od określonego `cameraOptions`:
* `String` zawierający obraz zakodowany przy pomocy base64.
* `String` reprezentujący lokalizację pliku obrazu w lokalnym magazynie (domyślnie).
Może rób, co chcesz z zakodowany obraz lub identyfikatora URI, na przykład:
* Przedstawić obraz w tagu `<img>`, jak w przykładzie poniżej
* Zapisać lokalnie dane (`LocalStorage`, [Lawnchair][1], etc.)
* Wysłać dane na zdalny serwer
[1]: http://brianleroux.github.com/lawnchair/
**Uwaga**: zdjęcie rozdzielczości na nowsze urządzenia jest bardzo dobry. Zdjęcia wybrane z galerii urządzenia są nie przeskalowanych w dół do niższej jakości, nawet jeśli określono parametr `quality`. Aby uniknąć typowych problemów z pamięci, zestaw `Camera.destinationType` `FILE_URI` zamiast `DATA_URL`.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Przeglądarka
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Preferencje (iOS)
* **CameraUsesGeolocation** (boolean, wartość domyślna to false). Do przechwytywania JPEG, zestaw do true, aby uzyskać danych geolokalizacyjnych w nagłówku EXIF. To spowoduje wniosek o geolokalizacji uprawnienia, jeśli zestaw na wartość true.
<preference name="CameraUsesGeolocation" value="false" />
### Amazon ogień OS dziwactwa
Amazon ogień OS używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności cordova.
### Dziwactwa Androida
Android używa intencje do rozpoczęcia działalności aparatu na urządzenie do przechwytywania obrazów, i na telefony z pamięci, Cordova aktywność może zostać zabity. W tym scenariuszu obraz mogą nie być wyświetlane po przywróceniu aktywności Cordova.
### Quirks przeglądarki
Może zwracać tylko zdjęcia jako obraz w formacie algorytmem base64.
### Firefox OS dziwactwa
Aparat plugin jest obecnie implementowane za pomocą [Działania sieci Web][2].
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### Dziwactwa iOS
W jednej z funkcji wywołania zwrotnego w tym JavaScript `alert()` może powodować problemy. Owinąć w `setTimeout()` umożliwia wybór obrazu iOS lub popover całkowicie zamknąć zanim wyświetli alert alert:
setTimeout(function() {
// do your thing here!
}, 0);
### Dziwactwa Windows Phone 7
Wywoływanie aparat native aplikacji, podczas gdy urządzenie jest podłączone przez Zune nie działa i powoduje błąd wywołania zwrotnego.
### Dziwactwa Tizen
Tizen obsługuje tylko `destinationType` z `Camera.DestinationType.FILE_URI` i `sourceType` z `Camera.PictureSourceType.PHOTOLIBRARY`.
### Przykład
Zrób zdjęcie i pobrać go jako kodowane algorytmem base64 obrazu:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Zrób zdjęcie i pobrać lokalizacji pliku obrazu:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
## CameraOptions
Opcjonalne parametry, aby dostosować ustawienia aparatu.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
### Opcje
* **quality**: Jakość zapisywanego obrazu, wyrażona w przedziale 0-100, gdzie 100 zazwyczaj jest maksymalną rozdzielczością bez strat w czasie kompresji pliku. Wartością domyślną jest 50. *(Liczba)* (Pamiętaj, że informacja o rozdzielczości aparatu jest niedostępna.)
* **destinationType**: Wybierz format zwracanej wartości. Wartością domyślną jest FILE_URI. Zdefiniowane w `navigator.camera.DestinationType` *(numer)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **sourceType**: Ustaw źródło obrazu. Wartością domyślną jest aparat fotograficzny. Zdefiniowane w `navigator.camera.PictureSourceType` *(numer)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit**: Pozwala na prostą edycję obrazu przed zaznaczeniem. *(Boolean)*
* **encodingType**: Wybierz plik obrazu zwracany jest kodowanie. Domyślnie jest JPEG. Zdefiniowane w `navigator.camera.EncodingType` *(numer)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth**: Szerokość w pikselach skalowanego obrazu. Musi być użyte z **targetHeight**. Współczynnik proporcji pozostaje stały. *(Liczba)*
* **targetHeight**: Wysokość w pikselach skalowanego obrazu. Musi być użyte z **targetWidth**. Współczynnik proporcji pozostaje stały. *(Liczba)*
* **mediaType**: Ustawia typ nośnika, z którego będzie wybrany. Działa tylko wtedy, gdy `PictureSourceType` jest `PHOTOLIBRARY` lub `SAVEDPHOTOALBUM`. Zdefiniowane w `nagivator.camera.MediaType` *(Liczba)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: Obraca obraz aby skorygować orientację urządzenia podczas przechwytywania. *(Boolean)*
* **saveToPhotoAlbum**: Po przechwyceniu zapisuje na urządzeniu obraz w albumie na zdjęcia. *(Boolean)*
* **popoverOptions**: Opcja tylko dla platformy iOS, która określa położenie wyskakującego okna na iPadzie. Zdefiniowane w `CameraPopoverOptions`.
* **cameraDirection**: Wybierz aparat do korzystania (lub z powrotem przodem). Wartością domyślną jest z powrotem. Zdefiniowane w `navigator.camera.Direction` *(numer)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### Amazon ogień OS dziwactwa
* Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery.
* Parametr `allowEdit` jest ignorowany.
* Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami.
### Dziwactwa Androida
* Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery.
* Parametr `allowEdit` jest ignorowany.
* Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami.
### Jeżyna 10 dziwactwa
* Parametr `quality` jest ignorowany.
* Parametr `allowEdit` jest ignorowany.
* Nie jest wspierane `Camera.MediaType`.
* Parametr `correctOrientation` jest ignorowany.
* Parametr `cameraDirection` jest ignorowany.
### Firefox OS dziwactwa
* Parametr `quality` jest ignorowany.
* `Camera.DestinationType`jest ignorowane i jest równa `1` (plik obrazu URI)
* Parametr `allowEdit` jest ignorowany.
* Ignoruje `PictureSourceType` parametr (użytkownik wybiera go w oknie dialogowym)
* Ignoruje`encodingType`
* Ignoruje `targetWidth` i`targetHeight`
* Nie jest wspierane `Camera.MediaType`.
* Parametr `correctOrientation` jest ignorowany.
* Parametr `cameraDirection` jest ignorowany.
### Dziwactwa iOS
* Ustaw `quality` poniżej 50 aby uniknąć błędów pamięci na niektórych urządzeniach.
* Podczas korzystania z `destinationType.FILE_URI` , zdjęcia są zapisywane w katalogu tymczasowego stosowania. Zawartość katalogu tymczasowego stosowania jest usuwany po zakończeniu aplikacji.
### Dziwactwa Tizen
* opcje nie są obsługiwane
* zawsze zwraca FILE URI
### Windows Phone 7 i 8 dziwactwa
* Parametr `allowEdit` jest ignorowany.
* Parametr `correctOrientation` jest ignorowany.
* Parametr `cameraDirection` jest ignorowany.
* Ignoruje `saveToPhotoAlbum` parametr. Ważne: Wszystkie zdjęcia zrobione aparatem wp7/8 cordova API są zawsze kopiowane do telefonu w kamerze. W zależności od ustawień użytkownika może to też oznaczać że obraz jest automatycznie przesłane do ich OneDrive. Potencjalnie może to oznaczać, że obraz jest dostępne dla szerszego grona odbiorców niż Twoja aplikacja przeznaczona. Jeśli ten bloker aplikacji, trzeba będzie wdrożenie CameraCaptureTask, opisane na msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> można także komentarz lub górę głosowanie powiązanych kwestii w [śledzenia błędów][3]
* Ignoruje `mediaType` Właściwość `cameraOptions` jako SDK Windows Phone nie umożliwiają wybór filmów z PHOTOLIBRARY.
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
funkcja wywołania zwrotnego PrzyBłędzie, która zawiera komunikat o błędzie.
function(message) {
// Show a helpful message
}
### Parametry
* **message**: Natywny kod komunikatu zapewniany przez urządzenie. *(Ciąg znaków)*
## cameraSuccess
onSuccess funkcji wywołania zwrotnego, który dostarcza dane obrazu.
function(imageData) {
// Do something with the image
}
### Parametry
* **imageData**: Dane obrazu kodowane przy pomocy Base64 *lub* URI pliku obrazu, w zależności od użycia `cameraOptions`. *(Ciąg znaków)*
### Przykład
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Uchwyt do okna dialogowego popover, stworzony przez `navigator.camera.getPicture`.
### Metody
* **setPosition**: Ustawia pozycję wyskakującego okna.
### Obsługiwane platformy
* iOS
### setPosition
Ustaw pozycję popover.
**Parametry**:
* `cameraPopoverOptions`: `CameraPopoverOptions`, która określa nową pozycję
### Przykład
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
tylko do iOS parametrami, które określić kotwicy element lokalizacji i strzałka kierunku popover, przy wyborze zdjęć z iPad biblioteki lub album.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
### CameraPopoverOptions
* **x**: współrzędna piksela x elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **y**: współrzędna piksela y elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **width**: szerokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **height**: wysokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
* **arrowDir**: Kierunek, który powinna wskazywać strzałka na wyskakującym oknie. Zdefiniowane w `Camera.PopoverArrowDirection` *(Liczba)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Należy pamiętać, że rozmiar popover może zmienić aby zmienić kierunek strzałki i orientacji ekranu. Upewnij się uwzględnić zmiany orientacji podczas określania położenia elementu kotwicy.
## navigator.camera.cleanup
Usuwa pośrednie zdjęcia zrobione przez aparat z czasowego składowania.
navigator.camera.cleanup( cameraSuccess, cameraError );
### Opis
Usuwa pliki obrazów pośrednich, które są przechowywane w pamięci tymczasowej po wywołaniu `camera.getPicture`. Ma zastosowanie tylko, gdy wartość `Camera.sourceType` jest równa `Camera.PictureSourceType.CAMERA` i `Camera.destinationType` jest równa `Camera.DestinationType.FILE_URI`.
### Obsługiwane platformy
* iOS
### Przykład
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,417 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
Этот плагин предоставляет API для съемки и для выбора изображения из библиотеки изображений системы.
cordova plugin add cordova-plugin-camera
## navigator.camera.getPicture
Снимает фотографию с помощью камеры, или получает фотографию из галереи изображений устройства. Изображение передается на функцию обратного вызова успешного завершения как `String` в base64-кодировке, или как URI указывающего на файл изображения. Метод возвращает объект `CameraPopoverHandle`, который может использоваться для перемещения инструмента выбора файла.
navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions );
### Описание
Функция `camera.getPicture` открывает приложение камеры устройства, которое позволяет снимать фотографии. Это происходит по умолчанию, когда `Camera.sourceType` равно `Camera.PictureSourceType.CAMERA` . Как только пользователь делает снимок,приложение камеры закрывается и приложение восстанавливается.
Если `Camera.sourceType` является `Camera.PictureSourceType.PHOTOLIBRARY` или `Camera.PictureSourceType.SAVEDPHOTOALBUM` , то показывается диалоговое окно, которое позволяет пользователям выбрать существующее изображение. Функция `camera.getPicture` возвращает объект `CameraPopoverHandle` объект, который может использоваться для перемещения диалога выбора изображения, например, при изменении ориентации устройства.
Возвращаемое значение отправляется в функцию обратного вызова `cameraSuccess` в одном из следующих форматов, в зависимости от параметра `cameraOptions` :
* A объект `String` содержащий фото изображение в base64-кодировке.
* Объект `String` представляющий расположение файла изображения на локальном хранилище (по умолчанию).
Вы можете сделать все, что угодно вы хотите с закодированным изображением или URI, например:
* Отобразить изображение с помощью тега `<img>`, как показано в примере ниже
* Сохранять данные локально (`LocalStorage`, [Lawnchair][1], и т.д.)
* Отправлять данные на удаленный сервер
[1]: http://brianleroux.github.com/lawnchair/
**Примечание**: разрешение фото на более новых устройствах является достаточно хорошим. Фотографии из галереи устройства не масштабируются к более низкому качеству, даже если указан параметр `quality`. Чтобы избежать общих проблем с памятью, установите `Camera.destinationType` в `FILE_URI` вместо `DATA_URL`.
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* BlackBerry 10
* Обозреватель
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Предпочтения (iOS)
* **CameraUsesGeolocation** (логическое значение, по умолчанию false). Для захвата изображения JPEG, значение true, чтобы получить данные геопозиционирования в заголовке EXIF. Это вызовет запрос на разрешения геолокации, если задано значение true.
<preference name="CameraUsesGeolocation" value="false" />
### Особенности Amazon Fire OS
Amazon Fire OS используют намерения для запуска активности камеры на устройстве для съемки фотографий, и на устройствах с низким объемам памяти, активность Cordova может быть завершена. В этом случае изображение может не появиться при восстановлении активности Cordova.
### Особенности Android
Android используют намерения для запуска активности камеры на устройстве для съемки фотографий, и на устройствах с низким объемам памяти, активность Cordova может быть завершена. В этом случае изображение может не появиться при восстановлении активности Cordova.
### Браузер причуды
Может возвращать только фотографии как изображения в кодировке base64.
### Особенности Firefox OS
Плагин Camera на данный момент реализован с использованием [Web Activities][2].
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### Особенности iOS
Включение функции JavaScript `alert()` в любой из функций обратного вызова функции может вызвать проблемы. Оберните вызов alert в `setTimeout()` для позволения окну выбора изображений iOS полностью закрыться перед отображение оповещения:
setTimeout(function() {/ / ваши вещи!}, 0);
### Особенности Windows Phone 7
Вызов встроенного приложения камеры, в то время как устройство подключено к Zune не работает, и инициирует обратный вызов для ошибки.
### Особенности Tizen
Tizen поддерживает только значение `destinationType` равное `Camera.DestinationType.FILE_URI` и значение `sourceType` равное `Camera.PictureSourceType.PHOTOLIBRARY`.
### Пример
Сделайте фотографию и получите его как изображение в base64-кодировке:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Сделайте фотографию и получить расположение файла с изображением:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
## CameraOptions
Необязательные параметры для настройки параметров камеры.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
### Параметры
* **quality**: качество сохраняемого изображения, выражается в виде числа в диапазоне от 0 до 100, где 100 является обычно полным изображением без потери качества при сжатии. Значение по умолчанию — 50. *(Число)* (Обратите внимание, что информация о разрешении камеры недоступна.)
* **параметр destinationType**: выберите формат возвращаемого значения. Значение по умолчанию — FILE_URI. Определяется в `navigator.camera.DestinationType` *(число)*
Camera.DestinationType = {
DATA_URL: 0, / / возвращение изображения в base64-кодировке строки
FILE_URI: 1, / / возврат файла изображения URI
NATIVE_URI: 2 / / возвращение образа собственного URI (например, Библиотека активов: / / на iOS или содержание: / / на андроиде)
};
* **тип источника**: установить источник рисунка. По умолчанию используется камера. Определяется в `navigator.camera.PictureSourceType` *(число)*
Camera.PictureSourceType = {
PHOTOLIBRARY: 0,
CAMERA: 1,
SAVEDPHOTOALBUM: 2
};
* **allowEdit**: позволит редактирование изображения средствами телефона перед окончательным выбором изображения. *(Логический)*
* **Тип_шифрования**: выберите возвращенный файл в кодировку. Значение по умолчанию — JPEG. Определяется в `navigator.camera.EncodingType` *(число)*
Camera.EncodingType = {
JPEG: 0, // возвращает изображение в формате JPEG
PNG: 1 // возвращает рисунок в формате PNG
};
* **targetWidth**: ширина изображения в пикселах к которой необходимо осуществить масштабирование. Это значение должно использоваться совместно с **targetHeight**. Пропорции изображения останутся неизменными. *(Число)*
* **targetHeight**: высота изображения в пикселах к которой необходимо осуществить масштабирование. Это значение должно использоваться совместно с **targetWidth**. Пропорции изображения останутся неизменными. *(Число)*
* **тип носителя**: Установите источник получения изображения, из которого надо выбрать изображение. Работает только если `PictureSourceType` равно `PHOTOLIBRARY` или `SAVEDPHOTOALBUM` . Определяется в `nagivator.camera.MediaType` *(число)*
Camera.MediaType = {
PICTURE: 0, / / разрешить выбор только сохраненных изображений. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation**: вращает изображение, чтобы внести исправления к ориентации устройства во время захвата. *(Логический)*
* **saveToPhotoAlbum**: сохранить изображение в фотоальбом на устройстве после захвата. *(Логическое)*
* **popoverOptions**: только для iOS параметры, которые определяют местоположение инструмента в iPad. Определены в`CameraPopoverOptions`.
* **cameraDirection**: выбрать камеру для использования (передней или задней стороне). Значение по умолчанию — обратно. Определяется в `navigator.camera.Direction` *(число)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### Особенности Amazon Fire OS
* Любое значение `cameraDirection` возвращает фотографию сделанную задней камерой.
* Игнорирует параметр `allowEdit`.
* Оба параметра `Camera.PictureSourceType.PHOTOLIBRARY` и `Camera.PictureSourceType.SAVEDPHOTOALBUM` отображают один и тот же фотоальбом.
### Особенности Android
* Любое значение `cameraDirection` возвращает фотографию сделанную задней камерой.
* Игнорирует параметр `allowEdit`.
* Оба параметра `Camera.PictureSourceType.PHOTOLIBRARY` и `Camera.PictureSourceType.SAVEDPHOTOALBUM` отображают один и тот же фотоальбом.
### Особенности BlackBerry 10
* Игнорирует `quality` параметр.
* Игнорирует параметр `allowEdit`.
* `Camera.MediaType` не поддерживается.
* Игнорирует параметр `correctOrientation`.
* Игнорирует параметр `cameraDirection`.
### Особенности Firefox OS
* Игнорирует `quality` параметр.
* Значение `Camera.DestinationType` игнорируется и равно `1` (URI для файла изображения)
* Игнорирует параметр `allowEdit`.
* Игнорирует параметр `PictureSourceType` (пользователь выбирает его в диалоговом окне)
* Игнорирует параметр `encodingType`
* Игнорирует `targetWidth` и `targetHeight`
* `Camera.MediaType` не поддерживается.
* Игнорирует параметр `correctOrientation`.
* Игнорирует параметр `cameraDirection`.
### Особенности iOS
* Установите `quality` ниже 50, для того чтобы избежать ошибок памяти на некоторых устройствах.
* При использовании `destinationType.FILE_URI` , фотографии сохраняются во временном каталоге приложения. Содержимое приложения временного каталога удаляется при завершении приложения.
### Особенности Tizen
* options, не поддерживается
* всегда возвращает URI файла
### Особенности Windows Phone 7 и 8
* Игнорирует параметр `allowEdit`.
* Игнорирует параметр `correctOrientation`.
* Игнорирует параметр `cameraDirection`.
* Игнорирует `saveToPhotoAlbum` параметр. Важно: Все изображения, снятые камерой wp7/8 cordova API всегда копируются в рулон камеры телефона. В зависимости от параметров пользователя это также может означать, что изображение автоматически загружены на их OneDrive. Потенциально это может означать, что этот образ доступен для более широкой аудитории, чем ваше приложение предназначено. Если этот блокатор для вашего приложения, вам нужно будет осуществить CameraCaptureTask, как описано на сайте msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> вы можете также комментарий или вверх голосование связанный с этим вопрос [отслеживания][3]
* Игнорирует свойство `mediaType` объекта `cameraOptions` так как Windows Phone SDK не предоставляет способ выбрать видео из PHOTOLIBRARY.
[3]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
Функция обратного вызова вызываемая в случае возникновения ошибки.
function(message) {
// Show a helpful message
}
### Параметры
* **сообщение**: сообщение об ошибке предоставляемое платформой устройства. *(Строка)*
## cameraSuccess
Функция обратного вызова onSuccess, получающая данные изображения.
function(imageData) {
// Do something with the image
}
### Параметры
* **imageData**: Данные изображения в Base64 кодировке, *или* URI, в зависимости от применяемых параметров `cameraOptions`. *(Строка)*
### Пример
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
Дескриптор диалогового окна инструмента, созданный `navigator.camera.getPicture`.
### Методы
* **setPosition**: Задайте положение инструмента выбора изображения.
### Поддерживаемые платформы
* iOS
### setPosition
Устанавливает положение инструмента выбора изображения.
**Параметры**:
* `cameraPopoverOptions`: Объект `CameraPopoverOptions`, определяющий новое положение
### Пример
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
Параметры только для iOS, которые определяют расположение элемента привязки и направление стрелки инструмента при выборе изображений из библиотеки изображений iPad или альбома.
{x: 0, y: 32, ширина: 320, высота: 480, arrowDir: Camera.PopoverArrowDirection.ARROW_ANY};
### CameraPopoverOptions
* **x**: x координата в пикселях элемента экрана, на котором закрепить инструмента. *(Число)*
* **x**: y координата в пикселях элемента экрана, на котором закрепить инструмента. *(Число)*
* **width**: ширина в пикселях элемента экрана, на котором закрепить инструмент выбора изображения. *(Число)*
* **height**: высота в пикселях элемента экрана, на котором закрепить инструмент выбора изображения. *(Число)*
* **arrowDir**: Направление, куда должна указывать стрелка на инструменте. Определено в `Camera.PopoverArrowDirection` *(число)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Обратите внимание, что размер инструмента может изменяться для корректировки в зависимости направлении стрелки и ориентации экрана. Убедитесь, что учитываете возможные изменения ориентации при указании расположения элемента привязки.
## navigator.camera.cleanup
Удаляет промежуточные фотографии, сделанные камерой из временного хранилища.
navigator.camera.cleanup( cameraSuccess, cameraError );
### Описание
Удаляет промежуточные файлы изображений, которые хранятся во временном хранилище после вызова метода `camera.getPicture` . Применяется только тогда, когда значение `Camera.sourceType` равно `Camera.PictureSourceType.CAMERA` и `Camera.destinationType` равняется `Camera.DestinationType.FILE_URI`.
### Поддерживаемые платформы
* iOS
### Пример
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,421 +0,0 @@
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg)](https://travis-ci.org/apache/cordova-plugin-camera)
這個外掛程式定義了一個全球 `navigator.camera` 物件,它提供了 API拍照從系統的圖像庫中選擇圖像。
雖然該物件附加到全球範圍內 `導航器`,它不可用直到 `deviceready` 事件之後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## 安裝
cordova plugin add cordova-plugin-camera
## API
* 相機
* navigator.camera.getPicture(success, fail, options)
* CameraOptions
* CameraPopoverHandle
* CameraPopoverOptions
* navigator.camera.cleanup
## navigator.camera.getPicture
需要一張照片,使用相機,或從設備的圖像庫檢索一張照片。 圖像被傳遞給成功回檔的 base64 編碼 `String`,或作為 URI 為影像檔。 該方法本身返回一個 `CameraPopoverHandle` 物件,它可以用來重新置放檔選擇氣泡框。
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### 說明
`camera.getPicture` 函數打開該設備的預設攝像頭應用程式,允許使用者拍照。 `Camera.sourceType` 等於 `Camera.PictureSourceType.CAMERA` 時,預設情況下,發生此行為。 一旦使用者打斷了他的照片,相機應用程式關閉,且應用程式還原。
如果 `Camera.sourceType``Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`,然後顯示一個對話方塊,允許使用者選擇一個現有的圖像。 `camera.getPicture` 函數返回一個 `CameraPopoverHandle` 物件,它可以用於重新置放圖像選擇的對話方塊,例如,當設備的方向變化。
傳回值是發送到 `cameraSuccess` 回呼函數中,在以下的格式,具體取決於指定的 `cameraOptions` 之一:
* A `String` 包含的 base64 編碼的照片圖像。
* A `String` 表示在本機存放區 (預設值) 上的影像檔位置。
你可以做任何你想要的編碼的圖像或 URI例如
* 呈現在圖像 `<img>` 標記,如下面的示例所示
* 保存本地的資料 `LocalStorage` [Lawnchair](http://brianleroux.github.com/lawnchair/),等等.)
* 將資料發佈到遠端伺服器
**注** 在更新設備上的照片解析度是很好。 選擇從設備的庫的照片是不壓縮螢幕使其以較低的品質,即使指定了一個 `quality` 參數。 要避免常見的記憶體問題,請將 `Camera.destinationType` 設置為 `FILE_URI`,而不是 `DATA_URL`.
#### 支援的平臺
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### 示例
拍一張照片,並檢索它作為一個 base64 編碼的圖像:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
拍一張照片和檢索圖像的檔位置:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### 首選項 iOS
* **CameraUsesGeolocation**(布林值,預設值為 false。 用於捕獲 jpeg 檔,設置為 true以在 EXIF 頭資訊中獲取地理定位資料。 這將觸發請求的地理位置的許可權,如果設置為 true。
<preference name="CameraUsesGeolocation" value="false" />
#### 亞馬遜火 OS 怪癖
亞馬遜火 OS 使用意圖啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。
#### Android 的怪癖
Android 使用意圖以啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。
#### 瀏覽器的怪癖
可以只返回照片作為 base64 編碼的圖像。
#### 火狐瀏覽器作業系統的怪癖
觀景窗外掛程式目前實施使用 [Web 活動](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
#### iOS 的怪癖
包括 JavaScript `alert ()` 中的回呼函數會導致問題。 包裝內 `setTimeout()` 允許 iOS 圖像選取器或氣泡框以完全關閉之前,警報將顯示警報:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 的怪癖
調用本機攝像頭應用程式,而通過 Zune 所連接的設備不能工作,並且觸發錯誤回檔。
#### Tizen 怪癖
泰只支援 `destinationType``Camera.DestinationType.FILE_URI``Camera.PictureSourceType.PHOTOLIBRARY``sourceType`.
## CameraOptions
要自訂相機設置的可選參數。
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
* **品質** 保存的圖像,表示為範圍 0-100100是通常全解析度無損失從檔案壓縮的品質。 預設值為 50。 *(人數)*(請注意相機的解析度有關的資訊是不可用)。
* **可** 選擇傳回值的格式。預設值是 FILE_URI。定義在 `navigator.camera.DestinationType` *(人數)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **時** 設置圖片的來源。預設值是觀景窗。定義在 `navigator.camera.PictureSourceType` *(人數)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit** 允許簡單編輯前選擇圖像。*(布林)*
* **encodingType** 選擇返回的影像檔的編碼。預設值為 JPEG。定義在 `navigator.camera.EncodingType` *(人數)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth** 向尺度圖像的圖元寬度。必須用**targetHeight**。縱橫比保持不變。*(人數)*
* **targetHeight** 以圖元為單位向尺度圖像的高度。必須用**targetWidth**。縱橫比保持不變。*(人數)*
* **媒體類型** 設置的媒體,從選擇類型。 時才起作用 `PictureSourceType``PHOTOLIBRARY``SAVEDPHOTOALBUM` 。 定義在 `nagivator.camera.MediaType` *(人數)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. 預設情況。 Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation** 旋轉圖像,該設備時捕獲的定向的正確。*(布林)*
* **saveToPhotoAlbum** 將圖像保存到相冊在設備上捕獲後。*(布林)*
* **popoverOptions** 只有 iOS 在 iPad 中指定氣泡框位置的選項。在中定義`CameraPopoverOptions`.
* **cameraDirection** 選擇相機以使用 (前面或後面-面向)。預設值是背。定義在 `navigator.camera.Direction` *(人數)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### 亞馬遜火 OS 怪癖
* 任何 `cameraDirection` 值回朝的照片中的結果。
* 忽略 `allowEdit` 參數。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的相冊。
#### Android 的怪癖
* 任何 `cameraDirection` 值回朝的照片中的結果。
* 安卓也用於作物活動 allowEdit即使作物應工作實際上將裁剪的圖像傳回給科爾多瓦那個唯一的作品一直是一個與谷歌加上照片應用程式捆綁在一起。 其他作物可能無法工作。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的相冊。
#### 黑莓 10 怪癖
* 忽略 `quality` 參數。
* 忽略 `allowEdit` 參數。
* `Camera.MediaType`不受支援。
* 忽略 `correctOrientation` 參數。
* 忽略 `cameraDirection` 參數。
#### 火狐瀏覽器作業系統的怪癖
* 忽略 `quality` 參數。
* `Camera.DestinationType`將被忽略並且等於 `1` (影像檔的 URI
* 忽略 `allowEdit` 參數。
* 忽略 `PictureSourceType` 參數 (使用者選擇它在對話方塊視窗中)
* 忽略`encodingType`
* 忽略了 `targetWidth``targetHeight`
* `Camera.MediaType`不受支援。
* 忽略 `correctOrientation` 參數。
* 忽略 `cameraDirection` 參數。
#### iOS 的怪癖
* 設置 `quality` 低於 50避免在某些設備上的記憶體不足錯誤。
* 當使用 `destinationType.FILE_URI` ,照片都保存在應用程式的臨時目錄。應用程式結束時,將刪除該應用程式的臨時目錄中的內容。
#### Tizen 怪癖
* 不支援的選項
* 總是返回一個檔的 URI
#### Windows Phone 7 和 8 怪癖
* 忽略 `allowEdit` 參數。
* 忽略 `correctOrientation` 參數。
* 忽略 `cameraDirection` 參數。
* 忽略 `saveToPhotoAlbum` 參數。 重要: 使用 wp7/8 科爾多瓦攝像頭 API 拍攝的所有圖像總是都複製到手機的相機膠捲。 根據使用者的設置,這可能也意味著圖像是自動上傳到他們另。 這有可能意味著的圖像,可以比你的應用程式的目的更多的觀眾。 如果此阻滯劑您的應用程式,您將需要實現 CameraCaptureTask 在 msdn 上記載: [HTTP://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx)你可能還評論或在[問題追蹤器](https://issues.apache.org/jira/browse/CB-2083)的向上投票的相關的問題
* 忽略了 `mediaType` 屬性的 `cameraOptions` 作為 Windows Phone SDK 並不提供從 PHOTOLIBRARY 中選擇視頻的方法。
## CameraError
onError 的回呼函數提供了一條錯誤訊息。
function(message) {
// Show a helpful message
}
#### 說明
* **message** 消息提供的設備的本機代碼。*String*
## cameraSuccess
提供的圖像資料的 onSuccess 回呼函數。
function(imageData) {
// Do something with the image
}
#### 說明
* **imageData** Base64 編碼進行編碼的圖像資料,*或*影像檔的 URI取決於 `cameraOptions` 效果。*String*
#### 示例
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
`navigator.camera.getPicture` 創建的氣泡框對話方塊的控制碼.
#### 說明
* **setPosition**: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### 支援的平臺
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### 示例
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS 僅指定氣泡框的錨元素的位置和箭頭方向,從 iPad 庫或專輯選擇圖像時的參數。
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### 說明
* **x** x 螢幕元素到其錨定氣泡框上的圖元座標。*(人數)*
* **y** 螢幕元素到其錨定氣泡框上的 y 圖元座標。*(人數)*
* **width** 寬度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)*
* **height** 高度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)*
* **arrowDir** 氣泡框上的箭頭應指向的方向。定義在 `Camera.PopoverArrowDirection` *(人數)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
請注意氣泡框的大小可能會更改箭頭的方向和螢幕的方向進行調整。 請確保帳戶方向更改時指定錨元素位置。
## navigator.camera.cleanup
刪除中間從臨時存儲攝像機所拍攝的照片。
navigator.camera.cleanup( cameraSuccess, cameraError );
#### 說明
刪除保留在臨時存儲在調用 `camera.getPicture` 後的中間的影像檔。 適用只有當 `Camera.sourceType` 的值等於 `Camera.PictureSourceType.CAMERA``Camera.destinationType` 等於 `Camera.DestinationType.FILE_URI`.
#### 支援的平臺
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### 示例
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,435 +0,0 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-camera
這個外掛程式定義了一個全球 `navigator.camera` 物件,它提供了 API拍照從系統的圖像庫中選擇圖像。
雖然該物件附加到全球範圍內 `導航器`,它不可用直到 `deviceready` 事件之後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## 安裝
cordova plugin add cordova-plugin-camera
## navigator.camera.getPicture
需要一張照片,使用相機,或從設備的圖像庫檢索一張照片。 圖像被傳遞給成功回檔的 base64 編碼 `String`,或作為 URI 為影像檔。 該方法本身返回一個 `CameraPopoverHandle` 物件,它可以用來重新置放檔選擇氣泡框。
navigator.camera.getPicture( cameraSuccess, cameraError, cameraOptions );
### 說明
`camera.getPicture` 函數打開該設備的預設攝像頭應用程式,允許使用者拍照。 `Camera.sourceType` 等於 `Camera.PictureSourceType.CAMERA` 時,預設情況下,發生此行為。 一旦使用者打斷了他的照片,相機應用程式關閉,且應用程式還原。
如果 `Camera.sourceType``Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM`,然後顯示一個對話方塊,允許使用者選擇一個現有的圖像。 `camera.getPicture` 函數返回一個 `CameraPopoverHandle` 物件,它可以用於重新置放圖像選擇的對話方塊,例如,當設備的方向變化。
傳回值是發送到 `cameraSuccess` 回呼函數中,在以下的格式,具體取決於指定的 `cameraOptions` 之一:
* A `String` 包含的 base64 編碼的照片圖像。
* A `String` 表示在本機存放區 (預設值) 上的影像檔位置。
你可以做任何你想要的編碼的圖像或 URI例如
* 呈現在圖像 `<img>` 標記,如下面的示例所示
* 保存本地的資料 `LocalStorage` [Lawnchair][1],等等.)
* 將資料發佈到遠端伺服器
[1]: http://brianleroux.github.com/lawnchair/
**注** 在更新設備上的照片解析度是很好。 選擇從設備的庫的照片是不壓縮螢幕使其以較低的品質,即使指定了一個 `quality` 參數。 要避免常見的記憶體問題,請將 `Camera.destinationType` 設置為 `FILE_URI`,而不是 `DATA_URL`.
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 瀏覽器
* 火狐瀏覽器的作業系統
* iOS
*
* Windows Phone 7 和 8
* Windows 8
### 首選項 iOS
* **CameraUsesGeolocation**(布林值,預設值為 false。 用於捕獲 jpeg 檔,設置為 true以在 EXIF 頭資訊中獲取地理定位資料。 這將觸發請求的地理位置的許可權,如果設置為 true。
<preference name="CameraUsesGeolocation" value="false" />
### 亞馬遜火 OS 怪癖
亞馬遜火 OS 使用意圖啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。
### Android 的怪癖
Android 使用意圖以啟動相機活動設備來捕捉圖像上, 和手機上記憶體不足,科爾多瓦活動可能被殺害。 在這種情況下,可能不會顯示圖像時恢復了科爾多瓦活動。
### 瀏覽器的怪癖
可以只返回照片作為 base64 編碼的圖像。
### 火狐瀏覽器作業系統的怪癖
觀景窗外掛程式目前實施使用 [Web 活動][2].
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
### iOS 的怪癖
包括 JavaScript `alert ()` 中的回呼函數會導致問題。 包裝內 `setTimeout()` 允許 iOS 圖像選取器或氣泡框以完全關閉之前,警報將顯示警報:
setTimeout(function() {
// do your thing here!
}, 0);
### Windows Phone 7 的怪癖
調用本機攝像頭應用程式,而通過 Zune 所連接的設備不能工作,並且觸發錯誤回檔。
### 泰怪癖
泰只支援 `destinationType``Camera.DestinationType.FILE_URI``Camera.PictureSourceType.PHOTOLIBRARY``sourceType`.
### 示例
拍一張照片,並檢索它作為一個 base64 編碼的圖像:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
拍一張照片和檢索圖像的檔位置:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
## CameraOptions
要自訂相機設置的可選參數。
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
### 選項
* **品質** 保存的圖像,表示為範圍 0-100100是通常全解析度無損失從檔案壓縮的品質。 預設值為 50。 *(人數)*(請注意相機的解析度有關的資訊是不可用)。
* **可** 選擇傳回值的格式。預設值是 FILE_URI。定義在 `navigator.camera.DestinationType` *(人數)*
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
* **時** 設置圖片的來源。預設值是觀景窗。定義在 `navigator.camera.PictureSourceType` *(人數)*
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
* **allowEdit** 允許簡單編輯前選擇圖像。*(布林)*
* **encodingType** 選擇返回的影像檔的編碼。預設值為 JPEG。定義在 `navigator.camera.EncodingType` *(人數)*
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
* **targetWidth** 向尺度圖像的圖元寬度。必須用**targetHeight**。縱橫比保持不變。*(人數)*
* **targetHeight** 以圖元為單位向尺度圖像的高度。必須用**targetWidth**。縱橫比保持不變。*(人數)*
* **媒體類型** 設置的媒體,從選擇類型。 時才起作用 `PictureSourceType``PHOTOLIBRARY``SAVEDPHOTOALBUM` 。 定義在 `nagivator.camera.MediaType` *(人數)*
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. 預設情況。 Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
* **correctOrientation** 旋轉圖像,該設備時捕獲的定向的正確。*(布林)*
* **saveToPhotoAlbum** 將圖像保存到相冊在設備上捕獲後。*(布林)*
* **popoverOptions** 只有 iOS 在 iPad 中指定氣泡框位置的選項。在中定義`CameraPopoverOptions`.
* **cameraDirection** 選擇相機以使用 (前面或後面-面向)。預設值是背。定義在 `navigator.camera.Direction` *(人數)*
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
### 亞馬遜火 OS 怪癖
* 任何 `cameraDirection` 值回朝的照片中的結果。
* 忽略 `allowEdit` 參數。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的相冊。
### Android 的怪癖
* 任何 `cameraDirection` 值結果在背面的照片。
* 忽略 `allowEdit` 參數。
* `Camera.PictureSourceType.PHOTOLIBRARY``Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的寫真集。
### 黑莓 10 的怪癖
* 忽略 `quality` 參數。
* 忽略 `allowEdit` 參數。
* `Camera.MediaType`不受支援。
* 忽略 `correctOrientation` 參數。
* 忽略 `cameraDirection` 參數。
### 火狐瀏覽器作業系統的怪癖
* 忽略 `quality` 參數。
* `Camera.DestinationType`將被忽略並且等於 `1` (影像檔的 URI
* 忽略 `allowEdit` 參數。
* 忽略 `PictureSourceType` 參數 (使用者選擇它在對話方塊視窗中)
* 忽略`encodingType`
* 忽略了 `targetWidth``targetHeight`
* `Camera.MediaType`不受支援。
* 忽略 `correctOrientation` 參數。
* 忽略 `cameraDirection` 參數。
### iOS 的怪癖
* 設置 `quality` 低於 50避免在某些設備上的記憶體不足錯誤。
* 當使用 `destinationType.FILE_URI` ,照片都保存在應用程式的臨時目錄。應用程式結束時,將刪除該應用程式的臨時目錄中的內容。
### 泰怪癖
* 不支援的選項
* 總是返回一個檔的 URI
### Windows Phone 7 和 8 的怪癖
* 忽略 `allowEdit` 參數。
* 忽略 `correctOrientation` 參數。
* 忽略 `cameraDirection` 參數。
* 忽略 `saveToPhotoAlbum` 參數。 重要: 使用 wp7/8 科爾多瓦攝像頭 API 拍攝的所有圖像總是都複製到手機的相機膠捲。 根據使用者的設置,這可能也意味著圖像是自動上傳到他們另。 這有可能意味著的圖像,可以比你的應用程式的目的更多的觀眾。 如果此阻滯劑您的應用程式,您將需要實現 CameraCaptureTask 在 msdn 上記載: [HTTP://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx][3]你可能還評論或在[問題追蹤器][4]的向上投票的相關的問題
* 忽略了 `mediaType` 屬性的 `cameraOptions` 作為 Windows Phone SDK 並不提供從 PHOTOLIBRARY 中選擇視頻的方法。
[3]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx
[4]: https://issues.apache.org/jira/browse/CB-2083
## CameraError
onError 的回呼函數提供了一條錯誤訊息。
function(message) {
// Show a helpful message
}
### 參數
* **message** 消息提供的設備的本機代碼。*String*
## cameraSuccess
提供的圖像資料的 onSuccess 回呼函數。
function(imageData) {
// Do something with the image
}
### 參數
* **imageData** Base64 編碼進行編碼的圖像資料,*或*影像檔的 URI取決於 `cameraOptions` 效果。*String*
### 示例
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
`navigator.camera.getPicture` 創建的氣泡框對話方塊的控制碼.
### 方法
* **setPosition** 設置氣泡框的位置。
### 支援的平臺
* iOS
### setPosition
設置氣泡框的位置。
**參數**
* `cameraPopoverOptions` `CameraPopoverOptions` ,指定新的位置
### 示例
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS 僅指定氣泡框的錨元素的位置和箭頭方向,從 iPad 庫或專輯選擇圖像時的參數。
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
### CameraPopoverOptions
* **x** x 螢幕元素到其錨定氣泡框上的圖元座標。*(人數)*
* **y** 螢幕元素到其錨定氣泡框上的 y 圖元座標。*(人數)*
* **width** 寬度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)*
* **height** 高度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)*
* **arrowDir** 氣泡框上的箭頭應指向的方向。定義在 `Camera.PopoverArrowDirection` *(人數)*
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
請注意氣泡框的大小可能會更改箭頭的方向和螢幕的方向進行調整。 請確保帳戶方向更改時指定錨元素位置。
## navigator.camera.cleanup
刪除中間從臨時存儲攝像機所拍攝的照片。
navigator.camera.cleanup( cameraSuccess, cameraError );
### 描述
刪除保留在臨時存儲在調用 `camera.getPicture` 後的中間的影像檔。 適用只有當 `Camera.sourceType` 的值等於 `Camera.PictureSourceType.CAMERA``Camera.destinationType` 等於 `Camera.DestinationType.FILE_URI`.
### 支援的平臺
* iOS
### 示例
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}

View File

@@ -1,443 +0,0 @@
---
title: Camera
description: Take pictures with the device camera.
---
{{>cdv-license~}}
|Android|iOS| Windows 8.1 Store | Windows 8.1 Phone | Windows 10 Store | Travis CI |
|:-:|:-:|:-:|:-:|:-:|:-:|
|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=android,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=ios,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-store,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-8.1-phone,PLUGIN=cordova-plugin-camera/)|[![Build Status](http://cordova-ci.cloudapp.net:8080/buildStatus/icon?job=cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera)](http://cordova-ci.cloudapp.net:8080/job/cordova-periodic-build/PLATFORM=windows-10-store,PLUGIN=cordova-plugin-camera/)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-camera.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-camera)
# cordova-plugin-camera
This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from
the system's image library.
{{>cdv-header device-ready-warning-obj='navigator.camera' npmName='cordova-plugin-camera' cprName='org.apache.cordova.camera' pluginName='Plugin Camera' repoUrl='https://github.com/apache/cordova-plugin-camera' }}
### iOS Quirks
Since iOS 10 it's mandatory to add a `NSCameraUsageDescription` and `NSPhotoLibraryUsageDescription` in the info.plist.
- `NSCameraUsageDescription` describes the reason that the app accesses the users camera.
- `NSPhotoLibraryUsageDescription` describes the reason the app accesses the user's photo library.
When the system prompts the user to allow access, this string is displayed as part of the dialog box.
To add this entry you can pass the following variables on plugin install.
- `CAMERA_USAGE_DESCRIPTION` for `NSCameraUsageDescription`
- `PHOTOLIBRARY_USAGE_DESCRIPTION` for `NSPhotoLibraryUsageDescription`
Example:
cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
If you don't pass the variable, the plugin will add an empty string as value.
---
# API Reference <a name="reference"></a>
{{#orphans~}}
{{>member-index}}
{{/orphans}}
* [CameraPopoverHandle](#module_CameraPopoverHandle)
* [CameraPopoverOptions](#module_CameraPopoverOptions)
---
{{#modules~}}
{{>header~}}
{{>body~}}
{{>members~}}
---
{{/modules}}
## `camera.getPicture` Errata
#### Example <a name="camera-getPicture-examples"></a>
Take a photo and retrieve the image's file location:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Take a photo and retrieve it as a Base64-encoded image:
/**
* Warning: Using DATA_URL is not recommended! The DATA_URL destination
* type is very memory intensive, even with a low quality setting. Using it
* can result in out of memory errors and application crashes. Use FILE_URI
* or NATIVE_URI instead.
*/
navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### Preferences (iOS)
- __CameraUsesGeolocation__ (boolean, defaults to false). For capturing JPEGs, set to true to get geolocation data in the EXIF header. This will trigger a request for geolocation permissions if set to true.
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon Fire OS Quirks <a name="camera-getPicture-quirks"></a>
Amazon Fire OS uses intents to launch the camera activity on the device to capture
images, and on phones with low memory, the Cordova activity may be killed. In this
scenario, the image may not appear when the Cordova activity is restored.
#### Android Quirks
Android uses intents to launch the camera activity on the device to capture
images, and on phones with low memory, the Cordova activity may be killed. In this
scenario, the result from the plugin call will be delivered via the resume event.
See [the Android Lifecycle guide][android_lifecycle]
for more information. The `pendingResult.result` value will contain the value that
would be passed to the callbacks (either the URI/URL or an error message). Check
the `pendingResult.pluginStatus` to determine whether or not the call was
successful.
#### Browser Quirks
Can only return photos as Base64-encoded image.
#### Firefox OS Quirks
Camera plugin is currently implemented using [Web Activities][web_activities].
#### iOS Quirks
Including a JavaScript `alert()` in either of the callback functions
can cause problems. Wrap the alert within a `setTimeout()` to allow
the iOS image picker or popover to fully close before the alert
displays:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 Quirks
Invoking the native camera application while the device is connected
via Zune does not work, and triggers an error callback.
#### Windows quirks
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
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
start page from scratch and success and error callbacks will never be called.
To avoid this we suggest using SPA pattern or call `camera.getPicture` only from your app's start page.
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)
#### Tizen Quirks
Tizen only supports a `destinationType` of
`Camera.DestinationType.FILE_URI` and a `sourceType` of
`Camera.PictureSourceType.PHOTOLIBRARY`.
## `CameraOptions` Errata <a name="CameraOptions-quirks"></a>
#### Amazon Fire OS Quirks
- Any `cameraDirection` value results in a back-facing photo.
- Ignores the `allowEdit` parameter.
- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
#### Android Quirks
- Any `cameraDirection` value results in a back-facing photo.
- **`allowEdit` is unpredictable on Android and it should not be used!** The Android implementation of this plugin tries to find and use an application on the user's device to do image cropping. The plugin has no control over what application the user selects to perform the image cropping and it is very possible that the user could choose an incompatible option and cause the plugin to fail. This sometimes works because most devices come with an application that handles cropping in a way that is compatible with this plugin (Google Plus Photos), but it is unwise to rely on that being the case. If image editing is essential to your application, consider seeking a third party library or plugin that provides its own image editing utility for a more robust solution.
- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
- Ignores the `encodingType` parameter if the image is unedited (i.e. `quality` is 100, `correctOrientation` is false, and no `targetHeight` or `targetWidth` are specified). The `CAMERA` source will always return the JPEG file given by the native camera and the `PHOTOLIBRARY` and `SAVEDPHOTOALBUM` sources will return the selected file in its existing encoding.
#### BlackBerry 10 Quirks
- Ignores the `quality` parameter.
- Ignores the `allowEdit` parameter.
- `Camera.MediaType` is not supported.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
#### Firefox OS Quirks
- Ignores the `quality` parameter.
- `Camera.DestinationType` is ignored and equals `1` (image file URI)
- Ignores the `allowEdit` parameter.
- Ignores the `PictureSourceType` parameter (user chooses it in a dialog window)
- Ignores the `encodingType`
- Ignores the `targetWidth` and `targetHeight`
- `Camera.MediaType` is not supported.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
#### iOS Quirks
- When using `destinationType.FILE_URI`, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends.
- When using `destinationType.NATIVE_URI` and `sourceType.CAMERA`, photos are saved in the saved photo album regardless on the value of `saveToPhotoAlbum` parameter.
- When using `destinationType.NATIVE_URI` and `sourceType.PHOTOLIBRARY` or `sourceType.SAVEDPHOTOALBUM`, all editing options are ignored and link is returned to original picture.
#### Tizen Quirks
- options not supported
- always returns a FILE URI
#### Windows Phone 7 and 8 Quirks
- Ignores the `allowEdit` parameter.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
- Ignores the `saveToPhotoAlbum` parameter. IMPORTANT: All images taken with the 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].
- Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.
[android_lifecycle]: http://cordova.apache.org/docs/en/dev/guide/platforms/android/lifecycle.html
[web_activities]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
[wp8_bug]: https://issues.apache.org/jira/browse/CB-2083
[msdn_wp8_docs]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx
## Sample: Take Pictures, Select Pictures from the Picture Library, and Get Thumbnails <a name="sample"></a>
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:
* Open the Camera app and [take a Picture](#takePicture)
* Take a picture and [return thumbnails](#getThumbnails) (resized picture)
* Take a picture and [generate a FileEntry object](#convert)
* [Select a file](#selectFile) from the picture library
* Select a JPEG image and [return thumbnails](#getFileThumbnails) (resized image)
* Select an image and [generate a FileEntry object](#convert)
## Take a Picture <a name="takePicture"></a>
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.
```js
function setOptions(srcType) {
var options = {
// Some common settings are 20, 50, and 100
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
// In this app, dynamically set the picture source, Camera or photo gallery
sourceType: srcType,
encodingType: Camera.EncodingType.JPEG,
mediaType: Camera.MediaType.PICTURE,
allowEdit: true,
correctOrientation: true //Corrects Android orientation quirks
}
return options;
}
```
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.
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.
```js
function openCamera(selection) {
var srcType = Camera.PictureSourceType.CAMERA;
var options = setOptions(srcType);
var func = createNewFileEntry;
navigator.camera.getPicture(function cameraSuccess(imageUri) {
displayImage(imageUri);
// You may choose to copy the picture, save it somewhere, or upload.
func(imageUri);
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
}
```
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.
```js
function displayImage(imgUri) {
var elem = document.getElementById('imageFile');
elem.src = imgUri;
}
```
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.
```html
<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 *">
```
## Take a Picture and Return Thumbnails (Resize the Picture) <a name="getThumbnails"></a>
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).
```js
function openCamera(selection) {
var srcType = Camera.PictureSourceType.CAMERA;
var options = setOptions(srcType);
var func = createNewFileEntry;
if (selection == "camera-thmb") {
options.targetHeight = 100;
options.targetWidth = 100;
}
navigator.camera.getPicture(function cameraSuccess(imageUri) {
// Do something
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
}
```
## Select a File from the Picture Library <a name="selectFile"></a>
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.
```js
function openFilePicker(selection) {
var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
var options = setOptions(srcType);
var func = createNewFileEntry;
navigator.camera.getPicture(function cameraSuccess(imageUri) {
// Do something
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
}
```
## Select an Image and Return Thumbnails (resized images) <a name="getFileThumbnails"></a>
Resizing a file selected with the file picker works just like resizing using the Camera app; set the `targetHeight` and `targetWidth` options.
```js
function openFilePicker(selection) {
var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
var options = setOptions(srcType);
var func = createNewFileEntry;
if (selection == "picker-thmb") {
// To downscale a selected image,
// Camera.EncodingType (e.g., JPEG) must match the selected image type.
options.targetHeight = 100;
options.targetWidth = 100;
}
navigator.camera.getPicture(function cameraSuccess(imageUri) {
// Do something with image
}, function cameraError(error) {
console.debug("Unable to obtain picture: " + error, "app");
}, options);
}
```
## Take a picture and get a FileEntry Object <a name="convert"></a>
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).
>*Note* You need the [File plugin](https://www.npmjs.com/package/cordova-plugin-file) to call `window.resolveLocalFileSystemURL`.
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.
```js
function getFileEntry(imgUri) {
window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {
// Do something with the FileEntry object, like write to it, upload it, etc.
// writeFile(fileEntry, imgUri);
console.log("got file: " + fileEntry.fullPath);
// displayFileData(fileEntry.nativeURL, "Native URL");
}, function () {
// If don't get the FileEntry (which may happen when testing
// on some emulators), copy to a new FileEntry.
createNewFileEntry(imgUri);
});
}
```
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.
>*Note* To see an example of writing to a FileEntry, see the [File plugin README](https://www.npmjs.com/package/cordova-plugin-file).
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.
```js
function createNewFileEntry(imgUri) {
window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {
// JPEG file
dirEntry.getFile("tempFile.jpeg", { create: true, exclusive: false }, function (fileEntry) {
// Do something with it, like write to it, upload it, etc.
// writeFile(fileEntry, imgUri);
console.log("got file: " + fileEntry.fullPath);
// displayFileData(fileEntry.fullPath, "File copied to");
}, onErrorCreateFile);
}, onErrorResolveUrl);
}
```

4234
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,63 +1,72 @@
{
"name": "cordova-plugin-camera",
"version": "2.4.1",
"version": "9.0.0-dev",
"description": "Cordova Camera Plugin",
"types": "./types/index.d.ts",
"cordova": {
"id": "cordova-plugin-camera",
"platforms": [
"firefoxos",
"android",
"amazon-fireos",
"ubuntu",
"ios",
"blackberry10",
"wp7",
"wp8",
"windows8",
"browser",
"windows"
"browser"
]
},
"repository": {
"type": "git",
"url": "https://github.com/apache/cordova-plugin-camera"
},
"repository": "github:apache/cordova-plugin-camera",
"bugs": "https://github.com/apache/cordova-plugin-camera/issues",
"keywords": [
"cordova",
"camera",
"ecosystem:cordova",
"cordova-firefoxos",
"cordova-android",
"cordova-amazon-fireos",
"cordova-ubuntu",
"cordova-ios",
"cordova-blackberry10",
"cordova-wp7",
"cordova-wp8",
"cordova-windows8",
"cordova-browser",
"cordova-windows"
"cordova-browser"
],
"scripts": {
"precommit": "npm run gen-docs && git add README.md",
"gen-docs": "jsdoc2md --template \"jsdoc2md/TEMPLATE.md\" \"www/**/*.js\" --plugin \"dmd-plugin-cordova-plugin\" > README.md",
"test": "npm run jshint",
"jshint": "node node_modules/jshint/bin/jshint www && node node_modules/jshint/bin/jshint src && node node_modules/jshint/bin/jshint tests"
"test": "npm run lint",
"lint": "eslint ."
},
"author": "Apache Software Foundation",
"license": "Apache-2.0",
"engines": {
"cordovaDependencies": {
"3.0.0": {
"cordova-android": ">=6.3.0"
},
"4.1.0": {
"cordova-android": ">=6.3.0",
"cordova": ">=7.1.0"
},
"5.0.0": {
"cordova-android": ">=9.0.0",
"cordova-ios": ">=5.1.0",
"cordova": ">=9.0.0"
},
"6.0.0": {
"cordova-android": ">=10.0.0",
"cordova-ios": ">=5.1.0",
"cordova": ">=9.0.0"
},
"7.0.0": {
"cordova-android": ">=12.0.0",
"cordova-ios": ">=5.1.0",
"cordova": ">=9.0.0"
},
"8.0.0": {
"cordova-android": ">=12.0.0",
"cordova-ios": ">=5.1.0",
"cordova": ">=9.0.0"
},
"9.0.0": {
"cordova-android": ">=12.0.0",
"cordova-ios": ">=7.0.0",
"cordova": ">=9.0.0"
},
"10.0.0": {
"cordova": ">100"
}
}
},
"devDependencies": {
"dmd-plugin-cordova-plugin": "^0.1.0",
"husky": "^0.10.1",
"jsdoc-to-markdown": "^1.2.0",
"jshint": "^2.6.0"
"@cordova/eslint-config": "^5.1.0"
}
}

View File

@@ -20,45 +20,29 @@
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:rim="http://www.blackberry.com/ns/widgets"
id="cordova-plugin-camera"
version="2.4.1">
version="9.0.0-dev">
<name>Camera</name>
<description>Cordova Camera Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,camera</keywords>
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-camera.git</repo>
<issue>https://issues.apache.org/jira/browse/CB/component/12320645</issue>
<repo>https://github.com/apache/cordova-plugin-camera</repo>
<issue>https://github.com/apache/cordova-plugin-camera/issues</issue>
<dependency id="cordova-plugin-compat" version="^1.1.0" />
<engines>
<engine name="cordova" version=">=9.0.0"/>
<engine name="cordova-android" version=">=12.0.0" />
<engine name="cordova-ios" version=">=7.0.0" />
</engines>
<js-module src="www/CameraConstants.js" name="Camera">
<clobbers target="Camera" />
</js-module>
<js-module src="www/CameraPopoverOptions.js" name="CameraPopoverOptions">
<clobbers target="CameraPopoverOptions" />
</js-module>
<js-module src="www/Camera.js" name="camera">
<clobbers target="navigator.camera" />
</js-module>
<!-- firefoxos -->
<platform name="firefoxos">
<config-file target="config.xml" parent="/*">
<feature name="Camera">
<param name="firefoxos-package" value="Camera" />
</feature>
</config-file>
<js-module src="src/firefoxos/CameraProxy.js" name="CameraProxy">
<runs />
</js-module>
</platform>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
@@ -66,77 +50,45 @@
<param name="android-package" value="org.apache.cordova.camera.CameraLauncher"/>
</feature>
</config-file>
<config-file target="AndroidManifest.xml" parent="/*">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</config-file>
<config-file target="AndroidManifest.xml" parent="application">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:name="org.apache.cordova.camera.FileProvider"
android:authorities="${applicationId}.cordova.plugin.camera.provider"
android:exported="false"
android:grantUriPermissions="true" >
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
android:resource="@xml/camera_provider_paths"/>
</provider>
</config-file>
<config-file target="AndroidManifest.xml" parent="queries">
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
<intent>
<action android:name="android.intent.action.GET_CONTENT" />
</intent>
<intent>
<action android:name="android.intent.action.PICK" />
</intent>
<intent>
<action android:name="com.android.camera.action.CROP" />
<data android:scheme="content" android:mimeType="image/*"/>
</intent>
</config-file>
<source-file src="src/android/CameraLauncher.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/CordovaUri.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/FileHelper.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/ExifHelper.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/xml/provider_paths.xml" target-dir="res/xml" />
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<framework src="com.android.support:support-v4:24.1.1+" />
<source-file src="src/android/FileProvider.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/GalleryPathVO.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/xml/camera_provider_paths.xml" target-dir="res/xml" />
<preference name="ANDROIDX_CORE_VERSION" default="1.6.+"/>
<framework src="androidx.core:core:$ANDROIDX_CORE_VERSION" />
</platform>
<!-- amazon-fireos -->
<platform name="amazon-fireos">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Camera">
<param name="android-package" value="org.apache.cordova.camera.CameraLauncher"/>
</feature>
</config-file>
<config-file target="AndroidManifest.xml" parent="/*">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</config-file>
<source-file src="src/android/CameraLauncher.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/FileHelper.java" target-dir="src/org/apache/cordova/camera" />
<source-file src="src/android/ExifHelper.java" target-dir="src/org/apache/cordova/camera" />
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
</platform>
<!-- ubuntu -->
<platform name="ubuntu">
<config-file target="config.xml" parent="/*">
<feature name="Camera">
<param policy_group="camera" policy_version="1" />
</feature>
</config-file>
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<header-file src="src/ubuntu/camera.h" />
<source-file src="src/ubuntu/camera.cpp" />
<resource-file src="src/ubuntu/back.png" />
<resource-file src="src/ubuntu/CaptureWidget.qml" />
<resource-file src="src/ubuntu/shoot.png" />
<resource-file src="src/ubuntu/toolbar-left.png" />
<resource-file src="src/ubuntu/toolbar-middle.png" />
<resource-file src="src/ubuntu/toolbar-right.png" />
</platform>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
@@ -146,10 +98,6 @@
<preference name="CameraUsesGeolocation" value="false" />
</config-file>
<js-module src="www/ios/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<header-file src="src/ios/UIImage+CropScaleOrientation.h" />
<source-file src="src/ios/UIImage+CropScaleOrientation.m" />
<header-file src="src/ios/CDVCamera.h" />
@@ -165,95 +113,8 @@
<framework src="CoreGraphics.framework" />
<framework src="AVFoundation.framework" />
<preference name="CAMERA_USAGE_DESCRIPTION" default=" " />
<config-file target="*-Info.plist" parent="NSCameraUsageDescription">
<string>$CAMERA_USAGE_DESCRIPTION</string>
</config-file>
<preference name="PHOTOLIBRARY_USAGE_DESCRIPTION" default=" " />
<config-file target="*-Info.plist" parent="NSPhotoLibraryUsageDescription">
<string>$PHOTOLIBRARY_USAGE_DESCRIPTION</string>
</config-file>
<config-file target="*-Info.plist" parent="NSLocationWhenInUseUsageDescription">
<string></string>
</config-file>
</platform>
<!-- blackberry10 -->
<platform name="blackberry10">
<source-file src="src/blackberry10/index.js" target-dir="Camera" />
<config-file target="www/config.xml" parent="/widget">
<feature name="Camera" value="Camera"/>
</config-file>
<config-file target="www/config.xml" parent="/widget/rim:permissions">
<rim:permit>access_shared</rim:permit>
<rim:permit>use_camera</rim:permit>
</config-file>
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<asset src="www/blackberry10/assets" target="chrome" />
</platform>
<!-- wp7 -->
<platform name="wp7">
<config-file target="config.xml" parent="/*">
<feature name="Camera">
<param name="wp-package" value="Camera"/>
</feature>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_ISV_CAMERA" />
<Capability Name="ID_CAP_MEDIALIB" />
</config-file>
<source-file src="src/wp/Camera.cs" />
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
</platform>
<!-- wp8 -->
<platform name="wp8">
<config-file target="config.xml" parent="/*">
<feature name="Camera">
<param name="wp-package" value="Camera"/>
</feature>
</config-file>
<config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
<Capability Name="ID_CAP_ISV_CAMERA" />
<Capability Name="ID_CAP_MEDIALIB_PHOTO"/>
</config-file>
<source-file src="src/wp/Camera.cs" />
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
</platform>
<!-- windows8 -->
<platform name="windows8">
<config-file target="package.appxmanifest" parent="/Package/Capabilities">
<Capability Name="picturesLibrary" />
<DeviceCapability Name="webcam" />
</config-file>
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<js-module src="src/windows/CameraProxy.js" name="CameraProxy">
<runs />
</js-module>
</platform>
<!-- browser -->
<platform name="browser">
<config-file target="config.xml" parent="/*">
@@ -267,19 +128,4 @@
</js-module>
</platform>
<!-- windows -->
<platform name="windows">
<config-file target="package.appxmanifest" parent="/Package/Capabilities">
<DeviceCapability Name="webcam" />
</config-file>
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
<clobbers target="CameraPopoverHandle" />
</js-module>
<js-module src="src/windows/CameraProxy.js" name="CameraProxy">
<runs />
</js-module>
</platform>
</plugin>

File diff suppressed because it is too large Load Diff

View File

@@ -1,104 +0,0 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import java.io.File;
/*
* This class exists because Andorid FilesProvider doesn't work on Android 4.4.4 and below and throws
* weird errors. I'm not sure why writing to shared cache directories is somehow verboten, but it is
* and this error is irritating for a Compatibility library to have.
*
*/
public class CordovaUri {
private Uri androidUri;
private String fileName;
private Uri fileUri;
/*
* We always expect a FileProvider string to be passed in for the file that we create
*
*/
CordovaUri (Uri inputUri)
{
//Determine whether the file is a content or file URI
if(inputUri.getScheme().equals("content"))
{
androidUri = inputUri;
fileName = getFileNameFromUri(androidUri);
fileUri = Uri.parse("file://" + fileName);
}
else
{
fileUri = inputUri;
fileName = FileHelper.stripFileProtocol(inputUri.toString());
}
}
public Uri getFileUri()
{
return fileUri;
}
public String getFilePath()
{
return fileName;
}
/*
* This only gets called by takePicture
*/
public Uri getCorrectUri()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
return androidUri;
else
return fileUri;
}
/*
* This is dirty, but it does the job.
*
* Since the FilesProvider doesn't really provide you a way of getting a URL from the file,
* and since we actually need the Camera to create the file for us most of the time, we don't
* actually write the file, just generate the location based on a timestamp, we need to get it
* back from the Intent.
*
* However, the FilesProvider preserves the path, so we can at least write to it from here, since
* we own the context in this case.
*/
private String getFileNameFromUri(Uri uri) {
String fullUri = uri.toString();
String partial_path = fullUri.split("external_files")[1];
File external_storage = Environment.getExternalStorageDirectory();
String path = external_storage.getAbsolutePath() + partial_path;
return path;
}
}

View File

@@ -19,6 +19,7 @@
package org.apache.cordova.camera;
import java.io.IOException;
import java.io.InputStream;
import android.media.ExifInterface;
@@ -56,6 +57,16 @@ public class ExifHelper {
this.inFile = new ExifInterface(filePath);
}
/**
* The file before it is compressed
*
* @param input
* @throws IOException
*/
public void createInFile(InputStream input) throws IOException {
this.inFile = new ExifInterface(input);
}
/**
* The file after it has been compressed
*

View File

@@ -19,7 +19,6 @@ package org.apache.cordova.camera;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
@@ -29,8 +28,8 @@ import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.LOG;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -44,29 +43,20 @@ public class FileHelper {
* Returns the real path of the given URI string.
* If the given URI string represents a content:// URI, the real path is retrieved from the media store.
*
* @param uriString the URI string of the audio/image/video
* @param uri the URI of the audio/image/video
* @param cordova the current application context
* @return the full path to the file
*/
@SuppressWarnings("deprecation")
public static String getRealPath(Uri uri, CordovaInterface cordova) {
String realPath = null;
if (Build.VERSION.SDK_INT < 11)
realPath = FileHelper.getRealPathFromURI_BelowAPI11(cordova.getActivity(), uri);
// SDK >= 11
else
realPath = FileHelper.getRealPathFromURI_API11_And_Above(cordova.getActivity(), uri);
return realPath;
return FileHelper.getRealPathFromURI(cordova.getActivity(), uri);
}
/**
* Returns the real path of the given URI.
* If the given URI is a content:// URI, the real path is retrieved from the media store.
*
* @param uri the URI of the audio/image/video
* @param uriString the URI string from which to obtain the input stream
* @param cordova the current application context
* @return the full path to the file
*/
@@ -75,11 +65,9 @@ public class FileHelper {
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API11_And_Above(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
public static String getRealPathFromURI(final Context context, final Uri uri) {
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
@@ -97,10 +85,21 @@ public class FileHelper {
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
if (id != null && id.length() > 0) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
return null;
}
} else {
return null;
}
}
// MediaProvider
else if (isMediaDocument(uri)) {
@@ -132,6 +131,9 @@ public class FileHelper {
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
if (isFileProviderUri(context, uri))
return getFileProviderPath(context, uri);
return getDataColumn(context, uri, null, null);
}
// File
@@ -142,22 +144,6 @@ public class FileHelper {
return null;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
try {
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
} catch (Exception e) {
result = null;
}
return result;
}
/**
* Returns an input stream based on given URI string.
*
@@ -177,6 +163,7 @@ public class FileHelper {
if (question > -1) {
uriString = uriString.substring(0, question);
}
if (uriString.startsWith("file:///android_asset/")) {
Uri uri = Uri.parse(uriString);
String relativePath = uri.getPath().substring(15);
@@ -206,6 +193,7 @@ public class FileHelper {
* @return a path without the "file://" prefix
*/
public static String stripFileProtocol(String uriString) {
if (uriString.startsWith("file://")) {
uriString = uriString.substring(7);
}
@@ -225,7 +213,7 @@ public class FileHelper {
}
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
/**
* Returns the mime type of the data specified by the given URI string.
*
@@ -233,7 +221,7 @@ public class FileHelper {
* @return the mime type of the specified data
*/
public static String getMimeType(String uriString, CordovaInterface cordova) {
String mimeType = null;
String mimeType;
Uri uri = Uri.parse(uriString);
if (uriString.startsWith("content://")) {
@@ -316,4 +304,28 @@ public class FileHelper {
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* @param context The Application context
* @param uri The Uri is checked by functions
* @return Whether the Uri authority is FileProvider
*/
public static boolean isFileProviderUri(final Context context, final Uri uri) {
final String packageName = context.getPackageName();
final String authority = new StringBuilder(packageName).append(".provider").toString();
return authority.equals(uri.getAuthority());
}
/**
* @param context The Application context
* @param uri The Uri is checked by functions
* @return File path or null if file is missing
*/
public static String getFileProviderPath(final Context context, final Uri uri)
{
final File appDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
final File file = new File(appDir, uri.getLastPathSegment());
return file.exists() ? file.toString(): null;
}
}

View File

@@ -0,0 +1,21 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.camera;
public class FileProvider extends androidx.core.content.FileProvider {}

View File

@@ -0,0 +1,43 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.camera;
public class GalleryPathVO {
private final String galleryPath;
private String picturesDirectory;
private String galleryFileName;
public GalleryPathVO(String picturesDirectory, String galleryFileName) {
this.picturesDirectory = picturesDirectory;
this.galleryFileName = galleryFileName;
this.galleryPath = this.picturesDirectory + "/" + this.galleryFileName;
}
public String getGalleryPath() {
return galleryPath;
}
public String getPicturesDirectory() {
return picturesDirectory;
}
public String getGalleryFileName() {
return galleryFileName;
}
}

View File

@@ -17,5 +17,5 @@
-->
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
<cache-path name="cache_files" path="org.apache.cordova.camera/" />
</paths>

View File

@@ -1,227 +0,0 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* globals qnx, FileError, PluginResult */
var PictureSourceType = {
PHOTOLIBRARY : 0, // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
CAMERA : 1, // Take picture from camera
SAVEDPHOTOALBUM : 2 // Choose image from picture library (same as PHOTOLIBRARY for Android)
},
DestinationType = {
DATA_URL: 0, // Return base64 encoded string
FILE_URI: 1, // Return file uri (content://media/external/images/media/2 for Android)
NATIVE_URI: 2 // Return native uri (eg. asset-library://... for iOS)
},
savePath = window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', '') + '/shared/camera/',
invokeAvailable = true;
//check for camera card - it isn't currently availble in work perimeter
window.qnx.webplatform.getApplication().invocation.queryTargets(
{
type: 'image/jpeg',
action: 'bb.action.CAPTURE',
target_type: 'CARD'
},
function (error, targets) {
invokeAvailable = !error && targets && targets instanceof Array &&
targets.filter(function (t) { return t.default === 'sys.camera.card'; }).length > 0;
}
);
//open a webview with getUserMedia camera card implementation when camera card not available
function showCameraDialog (done, cancel, fail) {
var wv = qnx.webplatform.createWebView(function () {
wv.url = 'local:///chrome/camera.html';
wv.allowQnxObject = true;
wv.allowRpc = true;
wv.zOrder = 1;
wv.setGeometry(0, 0, screen.width, screen.height);
wv.backgroundColor = 0x00000000;
wv.active = true;
wv.visible = true;
wv.on('UserMediaRequest', function (evt, args) {
wv.allowUserMedia(JSON.parse(args).id, 'CAMERA_UNIT_REAR');
});
wv.on('JavaScriptCallback', function (evt, data) {
var args = JSON.parse(data).args;
if (args[0] === 'cordova-plugin-camera') {
if (args[1] === 'cancel') {
cancel('User canceled');
} else if (args[1] === 'error') {
fail(args[2]);
} else {
saveImage(args[1], done, fail);
}
wv.un('JavaScriptCallback', arguments.callee);
wv.visible = false;
wv.destroy();
qnx.webplatform.getApplication().unlockRotation();
}
});
wv.on('Destroyed', function () {
wv.delete();
});
qnx.webplatform.getApplication().lockRotation();
qnx.webplatform.getController().dispatchEvent('webview.initialized', [wv]);
});
}
//create unique name for saved file (same pattern as BB10 camera app)
function imgName() {
var date = new Date(),
pad = function (n) { return n < 10 ? '0' + n : n; };
return 'IMG_' + date.getFullYear() + pad(date.getMonth() + 1) + pad(date.getDate()) + '_' +
pad(date.getHours()) + pad(date.getMinutes()) + pad(date.getSeconds()) + '.png';
}
//convert dataURI to Blob
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]),
mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0],
arrayBuffer = new ArrayBuffer(byteString.length),
ia = new Uint8Array(arrayBuffer),
i;
for (i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([new DataView(arrayBuffer)], { type: mimeString });
}
//save dataURI to file system and call success with path
function saveImage(data, success, fail) {
var name = savePath + imgName();
require('lib/webview').setSandbox(false);
window.webkitRequestFileSystem(window.PERSISTENT, 0, function (fs) {
fs.root.getFile(name, { create: true }, function (entry) {
entry.createWriter(function (writer) {
writer.onwriteend = function () {
success(name);
};
writer.onerror = fail;
writer.write(dataURItoBlob(data));
});
}, fail);
}, fail);
}
function encodeBase64(filePath, callback) {
var sandbox = window.qnx.webplatform.getController().setFileSystemSandbox, // save original sandbox value
errorHandler = function (err) {
var msg = "An error occured: ";
switch (err.code) {
case FileError.NOT_FOUND_ERR:
msg += "File or directory not found";
break;
case FileError.NOT_READABLE_ERR:
msg += "File or directory not readable";
break;
case FileError.PATH_EXISTS_ERR:
msg += "File or directory already exists";
break;
case FileError.TYPE_MISMATCH_ERR:
msg += "Invalid file type";
break;
default:
msg += "Unknown Error";
break;
}
// set it back to original value
window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
callback(msg);
},
gotFile = function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (e) {
// set it back to original value
window.qnx.webplatform.getController().setFileSystemSandbox = sandbox;
callback(this.result);
};
reader.readAsDataURL(file);
}, errorHandler);
},
onInitFs = function (fs) {
window.qnx.webplatform.getController().setFileSystemSandbox = false;
fs.root.getFile(filePath, {create: false}, gotFile, errorHandler);
};
window.webkitRequestFileSystem(window.TEMPORARY, 10 * 1024 * 1024, onInitFs, errorHandler); // set size to 10MB max
}
module.exports = {
takePicture: function (success, fail, args, env) {
var destinationType = JSON.parse(decodeURIComponent(args[1])),
sourceType = JSON.parse(decodeURIComponent(args[2])),
result = new PluginResult(args, env),
done = function (data) {
if (destinationType === DestinationType.FILE_URI) {
data = "file://" + data;
result.callbackOk(data, false);
} else {
encodeBase64(data, function (data) {
if (/^data:/.test(data)) {
data = data.slice(data.indexOf(",") + 1);
result.callbackOk(data, false);
} else {
result.callbackError(data, false);
}
});
}
},
cancel = function (reason) {
result.callbackError(reason, false);
},
invoked = function (error) {
if (error) {
result.callbackError(error, false);
}
};
switch(sourceType) {
case PictureSourceType.CAMERA:
if (invokeAvailable) {
window.qnx.webplatform.getApplication().cards.camera.open("photo", done, cancel, invoked);
} else {
showCameraDialog(done, cancel, fail);
}
break;
case PictureSourceType.PHOTOLIBRARY:
case PictureSourceType.SAVEDPHOTOALBUM:
window.qnx.webplatform.getApplication().cards.filePicker.open({
mode: "Picker",
type: ["picture"]
}, done, cancel, invoked);
break;
}
result.noResult(true);
}
};

View File

@@ -19,27 +19,27 @@
*
*/
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
const HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
function takePicture(success, error, opts) {
function takePicture (success, error, opts) {
if (opts && opts[2] === 1) {
capture(success, error, opts);
} else {
var input = document.createElement('input');
const input = document.createElement('input');
input.style.position = 'relative';
input.style.zIndex = HIGHEST_POSSIBLE_Z_INDEX;
input.className = 'cordova-camera-select';
input.type = 'file';
input.name = 'files[]';
input.onchange = function(inputEvent) {
var reader = new FileReader();
reader.onload = function(readerEvent) {
input.onchange = function (inputEvent) {
const reader = new FileReader(); /* eslint no-undef : 0 */
reader.onload = function (readerEvent) {
input.parentNode.removeChild(input);
var imageData = readerEvent.target.result;
const imageData = readerEvent.target.result;
return success(imageData.substr(imageData.indexOf(',') + 1));
return success(imageData);
};
reader.readAsDataURL(inputEvent.target.files[0]);
@@ -49,17 +49,17 @@ function takePicture(success, error, opts) {
}
}
function capture(success, errorCallback, opts) {
var localMediaStream;
var targetWidth = opts[3];
var targetHeight = opts[4];
function capture (success, errorCallback, opts) {
let localMediaStream;
let targetWidth = opts[3];
let targetHeight = opts[4];
targetWidth = targetWidth == -1?320:targetWidth;
targetHeight = targetHeight == -1?240:targetHeight;
targetWidth = targetWidth === -1 ? 320 : targetWidth;
targetHeight = targetHeight === -1 ? 240 : targetHeight;
var video = document.createElement('video');
var button = document.createElement('button');
var parent = document.createElement('div');
const video = document.createElement('video');
const button = document.createElement('button');
const parent = document.createElement('div');
parent.style.position = 'relative';
parent.style.zIndex = HIGHEST_POSSIBLE_Z_INDEX;
parent.className = 'cordova-camera-capture';
@@ -70,16 +70,15 @@ function capture(success, errorCallback, opts) {
video.height = targetHeight;
button.innerHTML = 'Capture!';
button.onclick = function() {
button.onclick = function () {
// create a canvas and capture a frame from video stream
var canvas = document.createElement('canvas');
const canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
canvas.getContext('2d').drawImage(video, 0, 0, targetWidth, targetHeight);
// convert image stored in canvas to base64 encoded image
var imageData = canvas.toDataURL('image/png');
imageData = imageData.replace('data:image/png;base64,', '');
const imageData = canvas.toDataURL('image/png');
// stop video stream, remove video and button.
// Note that MediaStream.stop() is deprecated as of Chrome 47.
@@ -100,24 +99,31 @@ function capture(success, errorCallback, opts) {
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
var successCallback = function(stream) {
const successCallback = function (stream) {
localMediaStream = stream;
video.src = window.URL.createObjectURL(localMediaStream);
if ('srcObject' in video) {
video.srcObject = localMediaStream;
} else {
video.src = window.URL.createObjectURL(localMediaStream);
}
video.play();
document.body.appendChild(parent);
};
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true, audio: true}, successCallback, errorCallback);
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(successCallback)
.catch(errorCallback);
} else if (navigator.getUserMedia) {
navigator.getUserMedia({ video: true, audio: false }, successCallback, errorCallback);
} else {
alert('Browser does not support camera :(');
}
}
module.exports = {
takePicture: takePicture,
cleanup: function(){}
takePicture,
cleanup: function () {}
};
require("cordova/exec/proxy").add("Camera",module.exports);
require('cordova/exec/proxy').add('Camera', module.exports);

View File

@@ -1,53 +0,0 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* globals MozActivity */
function takePicture(success, error, opts) {
var pick = new MozActivity({
name: "pick",
data: {
type: ["image/*"]
}
});
pick.onerror = error || function() {};
pick.onsuccess = function() {
// image is returned as Blob in this.result.blob
// we need to call success with url or base64 encoded image
if (opts && opts.destinationType === 0) {
// TODO: base64
return;
}
if (!opts || !opts.destinationType || opts.destinationType > 0) {
// url
return success(window.URL.createObjectURL(this.result.blob));
}
};
}
module.exports = {
takePicture: takePicture,
cleanup: function(){}
};
require("cordova/exec/proxy").add("Camera", module.exports);

View File

@@ -22,10 +22,29 @@
#import <CoreLocation/CLLocationManager.h>
#import <Cordova/CDVPlugin.h>
// Since iOS 14, we can use PHPickerViewController to select images from the photo library
//
// The following condition checks if the iOS 14 SDK is available for XCode
// which is true for XCode 12+. It does not check on runtime, if the device is running iOS 14+.
// For that API_AVAILABLE(ios(14)) is used for methods declarations and @available(iOS 14, *) for the code.
// The condition here makes just sure that the code can compile in XCode
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000 // Always true on XCode12+
// Import UniformTypeIdentifiers.h for using UTType* things, available since iOS 14,
// which replaces for e.g. kUTTypeImage with UTTypeImage, which must be used in the future instead
// Currently only used for PHPickerViewController
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
// Import PhotosUI framework for using PHPickerViewController
// PhotosUI is already available since iOS 8, but since we need it currently
// only for the PHPickerViewController, we import it conditionally here
#import <PhotosUI/PhotosUI.h>
#endif
enum CDVDestinationType {
DestinationTypeDataUrl = 0,
DestinationTypeFileUri,
DestinationTypeNativeUri
DestinationTypeFileUri
};
typedef NSUInteger CDVDestinationType;
@@ -53,10 +72,8 @@ typedef NSUInteger CDVMediaType;
@property (assign) BOOL allowsEditing;
@property (assign) BOOL correctOrientation;
@property (assign) BOOL saveToPhotoAlbum;
@property (strong) NSDictionary* popoverOptions;
@property (assign) UIImagePickerControllerCameraDevice cameraDirection;
@property (assign) BOOL popoverSupported;
@property (assign) BOOL usesGeolocation;
@property (assign) BOOL cropToSize;
@@ -70,7 +87,6 @@ typedef NSUInteger CDVMediaType;
@property (copy) NSString* callbackId;
@property (copy) NSString* postUrl;
@property (strong) UIPopoverController* pickerPopoverController;
@property (assign) BOOL cropToSize;
@property (strong) UIView* webView;
@@ -79,38 +95,48 @@ typedef NSUInteger CDVMediaType;
@end
// ======================================================================= //
// Use PHPickerViewController in iOS 14+ to select images from the photo library
// PHPickerViewControllerDelegate is only available since iOS 14
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000 // Always true on XCode12+
@interface CDVCamera : CDVPlugin <UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
CLLocationManagerDelegate,
PHPickerViewControllerDelegate>
{}
#else
@interface CDVCamera : CDVPlugin <UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIPopoverControllerDelegate,
CLLocationManagerDelegate>
{}
#endif
@property (strong) CDVCameraPicker* pickerController;
@property (strong) NSMutableDictionary *metadata;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong) NSData* data;
/*
* getPicture
*
* arguments:
* 1: this is the javascript function that will be called with the results, the first parameter passed to the
* javascript function is the picture as a Base64 encoded string
* 2: this is the javascript function to be called if there was an error
* options:
* quality: integer between 1 and 100
*/
- (void)takePicture:(CDVInvokedUrlCommand*)command;
- (void)cleanup:(CDVInvokedUrlCommand*)command;
- (void)repositionPopover:(CDVInvokedUrlCommand*)command;
// UIImagePickerControllerDelegate methods
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info;
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingImage:(UIImage*)image editingInfo:(NSDictionary*)editingInfo;
- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker;
// UINavigationControllerDelegate method
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
// CLLocationManagerDelegate methods
- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error;
// PHPickerViewController specific methods (iOS 14+)
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000 // Always true on XCode12+
- (void)showPHPicker:(NSString*)callbackId withOptions:(CDVPictureOptions*)pictureOptions API_AVAILABLE(ios(14));
- (void)processPHPickerImage:(UIImage*)image assetIdentifier:(NSString*)assetIdentifier callbackId:(NSString*)callbackId options:(CDVPictureOptions*)options API_AVAILABLE(ios(14));
- (void)finalizePHPickerImage:(UIImage*)image metadata:(NSDictionary*)metadata callbackId:(NSString*)callbackId options:(CDVPictureOptions*)options API_AVAILABLE(ios(14));
// PHPickerViewControllerDelegate method
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results API_AVAILABLE(ios(14));
#endif
@end

File diff suppressed because it is too large Load Diff

View File

@@ -1,118 +0,0 @@
/*
*
* Copyright 2013 Canonical Ltd.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import QtQuick 2.0
import QtMultimedia 5.0
Rectangle {
property string shootImagePath: "shoot.png"
function isSuffix(str, suffix) {
return String(str).substr(String(str).length - suffix.length) == suffix
}
id: ui
color: "#252423"
anchors.fill: parent
Camera {
objectName: "camera"
id: camera
onError: {
console.log(errorString);
}
videoRecorder.audioBitRate: 128000
imageCapture {
onImageSaved: {
root.exec("Camera", "onImageSaved", [path]);
ui.destroy();
}
}
}
VideoOutput {
id: output
source: camera
width: parent.width
height: parent.height
}
Item {
anchors.bottom: parent.bottom
width: parent.width
height: shootButton.height
BorderImage {
id: leftBackground
anchors.left: parent.left
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.right: middle.left
anchors.topMargin: units.dp(2)
anchors.bottomMargin: units.dp(2)
source: "toolbar-left.png"
Image {
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
anchors.leftMargin: parent.iconSpacing
source: "back.png"
width: units.gu(6)
height: units.gu(5)
MouseArea {
anchors.fill: parent
onClicked: {
root.exec("Camera", "cancel");
}
}
}
}
BorderImage {
id: middle
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
height: shootButton.height + units.gu(1)
width: shootButton.width
source: "toolbar-middle.png"
Image {
id: shootButton
width: units.gu(8)
height: width
anchors.horizontalCenter: parent.horizontalCenter
source: shootImagePath
MouseArea {
anchors.fill: parent
onClicked: {
camera.imageCapture.captureToLocation(ui.parent.plugin('Camera').generateLocation("jpg"));
}
}
}
}
BorderImage {
id: rightBackground
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.left: middle.right
anchors.topMargin: units.dp(2)
anchors.bottomMargin: units.dp(2)
source: "toolbar-right.png"
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -1,140 +0,0 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#include "camera.h"
#include <cordova.h>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QGraphicsObject>
#include <QCloseEvent>
#include <QQuickItem>
const char code[] = "\
var component, object; \
function createObject() { \
component = Qt.createComponent(%1); \
if (component.status == Component.Ready) \
finishCreation(); \
else \
component.statusChanged.connect(finishCreation); \
} \
function finishCreation() { \
CordovaWrapper.global.cameraPluginWidget = component.createObject(root, \
{root: root, cordova: cordova}); \
} \
createObject()";
Camera::Camera(Cordova *cordova):
CPlugin(cordova),
_lastScId(0),
_lastEcId(0) {
}
bool Camera::preprocessImage(QString &path) {
bool convertToPNG = (*_options.find("encodingType")).toInt() == Camera::PNG;
int quality = (*_options.find("quality")).toInt();
int width = (*_options.find("targetWidth")).toInt();
int height = (*_options.find("targetHeight")).toInt();
QImage image(path);
if (width <= 0)
width = image.width();
if (height <= 0)
height = image.height();
image = image.scaled(width, height, Qt::KeepAspectRatio, Qt::SmoothTransformation);
QFile oldImage(path);
QTemporaryFile newImage;
const char *type;
if (convertToPNG) {
path = generateLocation("png");
type = "png";
} else {
path = generateLocation("jpg");
type = "jpg";
}
image.save(path, type, quality);
oldImage.remove();
return true;
}
void Camera::onImageSaved(QString path) {
bool dataURL = _options.find("destinationType")->toInt() == Camera::DATA_URL;
QString cbParams;
if (preprocessImage(path)) {
QString absolutePath = QFileInfo(path).absoluteFilePath();
if (dataURL) {
QFile image(absolutePath);
image.open(QIODevice::ReadOnly);
QByteArray content = image.readAll().toBase64();
cbParams = QString("\"%1\"").arg(content.data());
image.remove();
} else {
cbParams = CordovaInternal::format(QString("file://localhost") + absolutePath);
}
}
this->callback(_lastScId, cbParams);
_lastEcId = _lastScId = 0;
}
void Camera::takePicture(int scId, int ecId, int quality, int destinationType, int/*sourceType*/, int targetWidth, int targetHeight, int encodingType,
int/*mediaType*/, bool/*allowEdit*/, bool/*correctOrientation*/, bool/*saveToPhotoAlbum*/, const QVariantMap &/*popoverOptions*/, int/*cameraDirection*/) {
if (_camera.isNull()) {
_camera = QSharedPointer<QCamera>(new QCamera());
}
if (((_lastScId || _lastEcId) && (_lastScId != scId && _lastEcId != ecId)) || !_camera->isAvailable() || _camera->lockStatus() != QCamera::Unlocked) {
this->cb(_lastEcId, "Device is busy");
return;
}
_options.clear();
_options.insert("quality", quality);
_options.insert("destinationType", destinationType);
_options.insert("targetWidth", targetWidth);
_options.insert("targetHeight", targetHeight);
_options.insert("encodingType", encodingType);
_lastScId = scId;
_lastEcId = ecId;
QString path = m_cordova->get_app_dir() + "/../qml/CaptureWidget.qml";
// TODO: relative url
QString qml = QString(code).arg(CordovaInternal::format(path));
m_cordova->execQML(qml);
}
void Camera::cancel() {
m_cordova->execQML("CordovaWrapper.global.cameraPluginWidget.destroy()");
this->cb(_lastEcId, "canceled");
_lastEcId = _lastScId = 0;
}

View File

@@ -1,86 +0,0 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
#ifndef CAMERA_H
#define CAMERA_H
#include <cplugin.h>
#include <QtCore>
#include <QQuickView>
#include <QCamera>
#include <QtMultimediaWidgets/QCameraViewfinder>
#include <QCameraImageCapture>
class Camera: public CPlugin {
Q_OBJECT
public:
explicit Camera(Cordova *cordova);
virtual const QString fullName() override {
return Camera::fullID();
}
virtual const QString shortName() override {
return "Camera";
}
static const QString fullID() {
return "Camera";
}
public slots:
void takePicture(int scId, int ecId, int quality, int destinationType, int/*sourceType*/, int targetWidth, int targetHeight, int encodingType,
int/*mediaType*/, bool/*allowEdit*/, bool/*correctOrientation*/, bool/*saveToPhotoAlbum*/, const QVariantMap &popoverOptions, int cameraDirection);
void cancel();
void onImageSaved(QString path);
QString generateLocation(const QString &extension) {
int i = 1;
for (;;++i) {
QString path = QString("%1/.local/share/%2/persistent/%3.%4").arg(QDir::homePath())
.arg(QCoreApplication::applicationName()).arg(i).arg(extension);
if (!QFileInfo(path).exists())
return path;
}
}
private:
bool preprocessImage(QString &path);
int _lastScId;
int _lastEcId;
QSharedPointer<QCamera> _camera;
QVariantMap _options;
protected:
enum DestinationType {
DATA_URL = 0,
FILE_URI = 1
};
enum EncodingType {
JPEG = 0,
PNG = 1
};
};
#endif // CAMERA_H

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1,882 +0,0 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/*jshint unused:true, undef:true, browser:true */
/*global Windows:true, URL:true, module:true, require:true, WinJS:true */
var Camera = require('./Camera');
var getAppData = function () {
return Windows.Storage.ApplicationData.current;
};
var encodeToBase64String = function (buffer) {
return Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
};
var OptUnique = Windows.Storage.CreationCollisionOption.generateUniqueName;
var CapMSType = Windows.Media.Capture.MediaStreamType;
var webUIApp = Windows.UI.WebUI.WebUIApplication;
var fileIO = Windows.Storage.FileIO;
var pickerLocId = Windows.Storage.Pickers.PickerLocationId;
module.exports = {
// args will contain :
// ... it is an array, so be careful
// 0 quality:50,
// 1 destinationType:Camera.DestinationType.FILE_URI,
// 2 sourceType:Camera.PictureSourceType.CAMERA,
// 3 targetWidth:-1,
// 4 targetHeight:-1,
// 5 encodingType:Camera.EncodingType.JPEG,
// 6 mediaType:Camera.MediaType.PICTURE,
// 7 allowEdit:false,
// 8 correctOrientation:false,
// 9 saveToPhotoAlbum:false,
// 10 popoverOptions:null
// 11 cameraDirection:0
takePicture: function (successCallback, errorCallback, args) {
var sourceType = args[2];
if (sourceType != Camera.PictureSourceType.CAMERA) {
takePictureFromFile(successCallback, errorCallback, args);
} else {
takePictureFromCamera(successCallback, errorCallback, args);
}
}
};
// https://msdn.microsoft.com/en-us/library/windows/apps/ff462087(v=vs.105).aspx
var windowsVideoContainers = [".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"];
var windowsPhoneVideoContainers = [".avi", ".3gp", ".3g2", ".wmv", ".3gp", ".3g2", ".mp4", ".m4v"];
// Default aspect ratio 1.78 (16:9 hd video standard)
var DEFAULT_ASPECT_RATIO = '1.8';
// Highest possible z-index supported across browsers. Anything used above is converted to this value.
var HIGHEST_POSSIBLE_Z_INDEX = 2147483647;
// Resize method
function resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) {
var tempPhotoFileName = "";
var targetContentType = "";
if (encodingType == Camera.EncodingType.PNG) {
tempPhotoFileName = "camera_cordova_temp_return.png";
targetContentType = "image/png";
} else {
tempPhotoFileName = "camera_cordova_temp_return.jpg";
targetContentType = "image/jpeg";
}
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting)
.then(function (storageFile) {
return fileIO.readBufferAsync(storageFile);
})
.then(function(buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64;
var image = new Image();
image.src = imageData;
image.onload = function() {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height;
var canvas = document.createElement('canvas');
var storageFileName;
canvas.width = imageWidth;
canvas.height = imageHeight;
canvas.getContext("2d").drawImage(this, 0, 0, imageWidth, imageHeight);
var fileContent = canvas.toDataURL(targetContentType).split(',')[1];
var storageFolder = getAppData().localFolder;
storageFolder.createFileAsync(tempPhotoFileName, OptUnique)
.then(function (storagefile) {
var content = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(fileContent);
storageFileName = storagefile.name;
return fileIO.writeBufferAsync(storagefile, content);
})
.done(function () {
successCallback("ms-appdata:///local/" + storageFileName);
}, errorCallback);
};
})
.done(null, function(err) {
errorCallback(err);
}
);
}
// Because of asynchronous method, so let the successCallback be called in it.
function resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight) {
fileIO.readBufferAsync(file).done( function(buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = "data:" + file.contentType + ";base64," + strBase64;
var image = new Image();
image.src = imageData;
image.onload = function() {
var ratio = Math.min(targetWidth / this.width, targetHeight / this.height);
var imageWidth = ratio * this.width;
var imageHeight = ratio * this.height;
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL(file.contentType);
// Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API.
var arr = finalFile.split(",");
var newStr = finalFile.substr(arr[0].length + 1);
successCallback(newStr);
};
}, function(err) { errorCallback(err); });
}
function takePictureFromFile(successCallback, errorCallback, args) {
// Detect Windows Phone
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
takePictureFromFileWP(successCallback, errorCallback, args);
} else {
takePictureFromFileWindows(successCallback, errorCallback, args);
}
}
function takePictureFromFileWP(successCallback, errorCallback, args) {
var mediaType = args[6],
destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5];
/*
Need to add and remove an event listener to catch activation state
Using FileOpenPicker will suspend the app and it's required to catch the PickSingleFileAndContinue
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/
var filePickerActivationHandler = function(eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickFileContinuation) {
var file = eventArgs.files[0];
if (!file) {
errorCallback("User didn't choose a file.");
webUIApp.removeEventListener("activated", filePickerActivationHandler);
return;
}
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
}
else {
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name);
}
else {
successCallback(URL.createObjectURL(storageFile));
}
}, function () {
errorCallback("Can't access localStorage folder.");
});
}
}
else {
if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer);
successCallback(strBase64);
}, errorCallback);
}
}
webUIApp.removeEventListener("activated", filePickerActivationHandler);
}
};
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
}
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsPhoneVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
}
else {
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
}
webUIApp.addEventListener("activated", filePickerActivationHandler);
fileOpenPicker.pickSingleFileAndContinue();
}
function takePictureFromFileWindows(successCallback, errorCallback, args) {
var mediaType = args[6],
destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5];
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
if (mediaType == Camera.MediaType.PICTURE) {
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.picturesLibrary;
}
else if (mediaType == Camera.MediaType.VIDEO) {
fileOpenPicker.fileTypeFilter.replaceAll(windowsVideoContainers);
fileOpenPicker.suggestedStartLocation = pickerLocId.videosLibrary;
}
else {
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
fileOpenPicker.suggestedStartLocation = pickerLocId.documentsLibrary;
}
fileOpenPicker.pickSingleFileAsync().done(function (file) {
if (!file) {
errorCallback("User didn't choose a file.");
return;
}
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
if (targetHeight > 0 && targetWidth > 0) {
resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType);
}
else {
var storageFolder = getAppData().localFolder;
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).done(function (storageFile) {
if(destinationType == Camera.DestinationType.NATIVE_URI) {
successCallback("ms-appdata:///local/" + storageFile.name);
}
else {
successCallback(URL.createObjectURL(storageFile));
}
}, function () {
errorCallback("Can't access localStorage folder.");
});
}
}
else {
if (targetHeight > 0 && targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, file, targetWidth, targetHeight);
} else {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 =encodeToBase64String(buffer);
successCallback(strBase64);
}, errorCallback);
}
}
}, function () {
errorCallback("User didn't choose a file.");
});
}
function takePictureFromCamera(successCallback, errorCallback, args) {
// Check if necessary API available
if (!Windows.Media.Capture.CameraCaptureUI) {
takePictureFromCameraWP(successCallback, errorCallback, args);
} else {
takePictureFromCameraWindows(successCallback, errorCallback, args);
}
}
function takePictureFromCameraWP(successCallback, errorCallback, args) {
// We are running on WP8.1 which lacks CameraCaptureUI class
// so we need to use MediaCapture class instead and implement custom UI for camera
var destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5],
saveToPhotoAlbum = args[9],
cameraDirection = args[11],
capturePreview = null,
cameraCaptureButton = null,
cameraCancelButton = null,
capture = null,
captureSettings = null,
CaptureNS = Windows.Media.Capture,
sensor = null;
function createCameraUI() {
// create style for take and cancel buttons
var buttonStyle = "width:45%;padding: 10px 16px;font-size: 18px;line-height: 1.3333333;color: #333;background-color: #fff;border-color: #ccc; border: 1px solid transparent;border-radius: 6px; display: block; margin: 20px; z-index: 1000;border-color: #adadad;";
// Create fullscreen preview
// z-order style element for capturePreview and cameraCancelButton elts
// is necessary to avoid overriding by another page elements, -1 sometimes is not enough
capturePreview = document.createElement("video");
capturePreview.style.cssText = "position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: " + (HIGHEST_POSSIBLE_Z_INDEX - 1) + ";";
// Create capture button
cameraCaptureButton = document.createElement("button");
cameraCaptureButton.innerText = "Take";
cameraCaptureButton.style.cssText = buttonStyle + "position: fixed; left: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
// Create cancel button
cameraCancelButton = document.createElement("button");
cameraCancelButton.innerText = "Cancel";
cameraCancelButton.style.cssText = buttonStyle + "position: fixed; right: 0; bottom: 0; margin: 20px; z-index: " + HIGHEST_POSSIBLE_Z_INDEX + ";";
capture = new CaptureNS.MediaCapture();
captureSettings = new CaptureNS.MediaCaptureInitializationSettings();
captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video;
}
function continueVideoOnFocus() {
// if preview is defined it would be stuck, play it
if (capturePreview) {
capturePreview.play();
}
}
function startCameraPreview() {
// Search for available camera devices
// This is necessary to detect which camera (front or back) we should use
var DeviceEnum = Windows.Devices.Enumeration;
var expectedPanel = cameraDirection === 1 ? DeviceEnum.Panel.front : DeviceEnum.Panel.back;
// Add focus event handler to capture the event when user suspends the app and comes back while the preview is on
window.addEventListener("focus", continueVideoOnFocus);
DeviceEnum.DeviceInformation.findAllAsync(DeviceEnum.DeviceClass.videoCapture).then(function (devices) {
if (devices.length <= 0) {
destroyCameraPreview();
errorCallback('Camera not found');
return;
}
devices.forEach(function(currDev) {
if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
captureSettings.videoDeviceId = currDev.id;
}
});
captureSettings.photoCaptureSource = Windows.Media.Capture.PhotoCaptureSource.photo;
return capture.initializeAsync(captureSettings);
}).then(function () {
// create focus control if available
var VideoDeviceController = capture.videoDeviceController;
var FocusControl = VideoDeviceController.focusControl;
if (FocusControl.supported === true) {
capturePreview.addEventListener('click', function () {
// Make sure function isn't called again before previous focus is completed
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
var preset = Windows.Media.Devices.FocusPreset.autoNormal;
var parent = this;
FocusControl.setPresetAsync(preset).done(function () {
// set the clicked attribute back to '0' to allow focus again
parent.setAttribute('clicked', '0');
});
});
}
// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
capturePreview.msZoom = true;
capturePreview.src = URL.createObjectURL(capture);
capturePreview.play();
// Bind events to controls
sensor = Windows.Devices.Sensors.SimpleOrientationSensor.getDefault();
if (sensor !== null) {
sensor.addEventListener("orientationchanged", onOrientationChange);
}
// add click events to capture and cancel buttons
cameraCaptureButton.addEventListener('click', onCameraCaptureButtonClick);
cameraCancelButton.addEventListener('click', onCameraCancelButtonClick);
// Change default orientation
if (sensor) {
setPreviewRotation(sensor.getCurrentOrientation());
} else {
setPreviewRotation(Windows.Graphics.Display.DisplayInformation.getForCurrentView().currentOrientation);
}
// Get available aspect ratios
var aspectRatios = getAspectRatios(capture);
// Couldn't find a good ratio
if (aspectRatios.length === 0) {
destroyCameraPreview();
errorCallback('There\'s not a good aspect ratio available');
return;
}
// add elements to body
document.body.appendChild(capturePreview);
document.body.appendChild(cameraCaptureButton);
document.body.appendChild(cameraCancelButton);
if (aspectRatios.indexOf(DEFAULT_ASPECT_RATIO) > -1) {
return setAspectRatio(capture, DEFAULT_ASPECT_RATIO);
} else {
// Doesn't support 16:9 - pick next best
return setAspectRatio(capture, aspectRatios[0]);
}
}).done(null, function (err) {
destroyCameraPreview();
errorCallback('Camera intitialization error ' + err);
});
}
function destroyCameraPreview() {
// If sensor is available, remove event listener
if (sensor !== null) {
sensor.removeEventListener('orientationchanged', onOrientationChange);
}
// Pause and dispose preview element
capturePreview.pause();
capturePreview.src = null;
// Remove event listeners from buttons
cameraCaptureButton.removeEventListener('click', onCameraCaptureButtonClick);
cameraCancelButton.removeEventListener('click', onCameraCancelButtonClick);
// Remove the focus event handler
window.removeEventListener("focus", continueVideoOnFocus);
// Remove elements
[capturePreview, cameraCaptureButton, cameraCancelButton].forEach(function (elem) {
if (elem /* && elem in document.body.childNodes */) {
document.body.removeChild(elem);
}
});
// Stop and dispose media capture manager
if (capture) {
capture.stopRecordAsync();
capture = null;
}
}
function captureAction() {
var encodingProperties,
fileName,
tempFolder = getAppData().temporaryFolder;
if (encodingType == Camera.EncodingType.PNG) {
fileName = 'photo.png';
encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createPng();
} else {
fileName = 'photo.jpg';
encodingProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg();
}
tempFolder.createFileAsync(fileName, OptUnique)
.then(function(tempCapturedFile) {
return new WinJS.Promise(function (complete) {
var photoStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
var finalStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
capture.capturePhotoToStreamAsync(encodingProperties, photoStream)
.then(function() {
return Windows.Graphics.Imaging.BitmapDecoder.createAsync(photoStream);
})
.then(function(dec) {
finalStream.size = 0; // BitmapEncoder requires the output stream to be empty
return Windows.Graphics.Imaging.BitmapEncoder.createForTranscodingAsync(finalStream, dec);
})
.then(function(enc) {
// We need to rotate the photo wrt sensor orientation
enc.bitmapTransform.rotation = orientationToRotation(sensor.getCurrentOrientation());
return enc.flushAsync();
})
.then(function() {
return tempCapturedFile.openAsync(Windows.Storage.FileAccessMode.readWrite);
})
.then(function(fileStream) {
return Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(finalStream, fileStream);
})
.done(function() {
photoStream.close();
finalStream.close();
complete(tempCapturedFile);
}, function() {
photoStream.close();
finalStream.close();
throw new Error("An error has occured while capturing the photo.");
});
});
})
.done(function(capturedFile) {
destroyCameraPreview();
savePhoto(capturedFile, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
}, function(err) {
destroyCameraPreview();
errorCallback(err);
});
}
function getAspectRatios(capture) {
var videoDeviceController = capture.videoDeviceController;
var photoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var videoAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var videoPreviewAspectRatios = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview).map(function (element) {
return (element.width / element.height).toFixed(1);
}).filter(function (element, index, array) { return (index === array.indexOf(element)); });
var allAspectRatios = [].concat(photoAspectRatios, videoAspectRatios, videoPreviewAspectRatios);
var aspectObj = allAspectRatios.reduce(function (map, item) {
if (!map[item]) {
map[item] = 0;
}
map[item]++;
return map;
}, {});
return Object.keys(aspectObj).filter(function (k) {
return aspectObj[k] === 3;
});
}
function setAspectRatio(capture, aspect) {
// Max photo resolution with desired aspect ratio
var videoDeviceController = capture.videoDeviceController;
var photoResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.photo)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
// Max video resolution with desired aspect ratio
var videoRecordResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoRecord)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
// Max video preview resolution with desired aspect ratio
var videoPreviewResolution = videoDeviceController.getAvailableMediaStreamProperties(CapMSType.videoPreview)
.filter(function (elem) {
return ((elem.width / elem.height).toFixed(1) === aspect);
})
.reduce(function (prop1, prop2) {
return (prop1.width * prop1.height) > (prop2.width * prop2.height) ? prop1 : prop2;
});
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.photo, photoResolution)
.then(function () {
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoPreview, videoPreviewResolution);
})
.then(function () {
return videoDeviceController.setMediaStreamPropertiesAsync(CapMSType.videoRecord, videoRecordResolution);
});
}
/**
* When Capture button is clicked, try to capture a picture and return
*/
function onCameraCaptureButtonClick() {
// Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
captureAction();
}
/**
* When Cancel button is clicked, destroy camera preview and return with error callback
*/
function onCameraCancelButtonClick() {
// Make sure user can't click more than once
if (this.getAttribute('clicked') === '1') {
return false;
} else {
this.setAttribute('clicked', '1');
}
destroyCameraPreview();
errorCallback('no image selected');
}
/**
* When the phone orientation change, get the event and change camera preview rotation
* @param {Object} e - SimpleOrientationSensorOrientationChangedEventArgs
*/
function onOrientationChange(e) {
setPreviewRotation(e.orientation);
}
/**
* Converts SimpleOrientation to a VideoRotation to remove difference between camera sensor orientation
* and video orientation
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
* @return {number} - Windows.Media.Capture.VideoRotation
*/
function orientationToRotation(orientation) {
// VideoRotation enumerable and BitmapRotation enumerable have the same values
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmaprotation.aspx
switch (orientation) {
// portrait
case Windows.Devices.Sensors.SimpleOrientation.notRotated:
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape
case Windows.Devices.Sensors.SimpleOrientation.rotated90DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.none;
// portrait-flipped (not supported by WinPhone Apps)
case Windows.Devices.Sensors.SimpleOrientation.rotated180DegreesCounterclockwise:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
// landscape-flipped
case Windows.Devices.Sensors.SimpleOrientation.rotated270DegreesCounterclockwise:
return Windows.Media.Capture.VideoRotation.clockwise180Degrees;
// faceup & facedown
default:
// Falling back to portrait default
return Windows.Media.Capture.VideoRotation.clockwise90Degrees;
}
}
/**
* Rotates the current MediaCapture's video
* @param {number} orientation - Windows.Devices.Sensors.SimpleOrientation
*/
function setPreviewRotation(orientation) {
capture.setPreviewRotation(orientationToRotation(orientation));
}
try {
createCameraUI();
startCameraPreview();
} catch (ex) {
errorCallback(ex);
}
}
function takePictureFromCameraWindows(successCallback, errorCallback, args) {
var destinationType = args[1],
targetWidth = args[3],
targetHeight = args[4],
encodingType = args[5],
allowCrop = !!args[7],
saveToPhotoAlbum = args[9],
WMCapture = Windows.Media.Capture,
cameraCaptureUI = new WMCapture.CameraCaptureUI();
cameraCaptureUI.photoSettings.allowCropping = allowCrop;
if (encodingType == Camera.EncodingType.PNG) {
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.png;
} else {
cameraCaptureUI.photoSettings.format = WMCapture.CameraCaptureUIPhotoFormat.jpeg;
}
// decide which max pixels should be supported by targetWidth or targetHeight.
var maxRes = null;
var UIMaxRes = WMCapture.CameraCaptureUIMaxPhotoResolution;
var totalPixels = targetWidth * targetHeight;
if (targetWidth == -1 && targetHeight == -1) {
maxRes = UIMaxRes.highestAvailable;
}
// Temp fix for CB-10539
/*else if (totalPixels <= 320 * 240) {
maxRes = UIMaxRes.verySmallQvga;
}*/
else if (totalPixels <= 640 * 480) {
maxRes = UIMaxRes.smallVga;
} else if (totalPixels <= 1024 * 768) {
maxRes = UIMaxRes.mediumXga;
} else if (totalPixels <= 3 * 1000 * 1000) {
maxRes = UIMaxRes.large3M;
} else if (totalPixels <= 5 * 1000 * 1000) {
maxRes = UIMaxRes.veryLarge5M;
} else {
maxRes = UIMaxRes.highestAvailable;
}
cameraCaptureUI.photoSettings.maxResolution = maxRes;
var cameraPicture;
// define focus handler for windows phone 10.0
var savePhotoOnFocus = function () {
window.removeEventListener("focus", savePhotoOnFocus);
// call only when the app is in focus again
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
};
// if windows phone 10, add and delete focus eventHandler to capture the focus back from cameraUI to app
if (navigator.appVersion.indexOf('Windows Phone 10.0') >= 0) {
window.addEventListener("focus", savePhotoOnFocus);
}
cameraCaptureUI.captureFileAsync(WMCapture.CameraCaptureUIMode.photo).done(function (picture) {
if (!picture) {
errorCallback("User didn't capture a photo.");
// Remove the focus handler if present
window.removeEventListener("focus", savePhotoOnFocus);
return;
}
cameraPicture = picture;
// If not windows 10, call savePhoto() now. If windows 10, wait for the app to be in focus again
if (navigator.appVersion.indexOf('Windows Phone 10.0') < 0) {
savePhoto(cameraPicture, {
destinationType: destinationType,
targetHeight: targetHeight,
targetWidth: targetWidth,
encodingType: encodingType,
saveToPhotoAlbum: saveToPhotoAlbum
}, successCallback, errorCallback);
}
}, function () {
errorCallback("Fail to capture a photo.");
window.removeEventListener("focus", savePhotoOnFocus);
});
}
function savePhoto(picture, options, successCallback, errorCallback) {
// success callback for capture operation
var success = function(picture) {
if (options.destinationType == Camera.DestinationType.FILE_URI || options.destinationType == Camera.DestinationType.NATIVE_URI) {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImage(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight, options.encodingType);
} else {
picture.copyAsync(getAppData().localFolder, picture.name, OptUnique).done(function (copiedFile) {
successCallback("ms-appdata:///local/" + copiedFile.name);
},errorCallback);
}
} else {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImageBase64(successCallback, errorCallback, picture, options.targetWidth, options.targetHeight);
} else {
fileIO.readBufferAsync(picture).done(function(buffer) {
var strBase64 = encodeToBase64String(buffer);
picture.deleteAsync().done(function() {
successCallback(strBase64);
}, function(err) {
errorCallback(err);
});
}, errorCallback);
}
}
};
if (!options.saveToPhotoAlbum) {
success(picture);
return;
} else {
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
var saveFile = function(file) {
if (file) {
// Prevent updates to the remote version of the file until we're done
Windows.Storage.CachedFileManager.deferUpdates(file);
picture.moveAndReplaceAsync(file)
.then(function() {
// Let Windows know that we're finished changing the file so
// the other app can update the remote version of the file.
return Windows.Storage.CachedFileManager.completeUpdatesAsync(file);
})
.done(function(updateStatus) {
if (updateStatus === Windows.Storage.Provider.FileUpdateStatus.complete) {
success(picture);
} else {
errorCallback("File update status is not complete.");
}
}, errorCallback);
} else {
errorCallback("Failed to select a file.");
}
};
savePicker.suggestedStartLocation = pickerLocId.picturesLibrary;
if (options.encodingType === Camera.EncodingType.PNG) {
savePicker.fileTypeChoices.insert("PNG", [".png"]);
savePicker.suggestedFileName = "photo.png";
} else {
savePicker.fileTypeChoices.insert("JPEG", [".jpg"]);
savePicker.suggestedFileName = "photo.jpg";
}
// If Windows Phone 8.1 use pickSaveFileAndContinue()
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0) {
/*
Need to add and remove an event listener to catch activation state
Using FileSavePicker will suspend the app and it's required to catch the pickSaveFileContinuation
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn631755.aspx
*/
var fileSaveHandler = function(eventArgs) {
if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
var file = eventArgs.file;
saveFile(file);
webUIApp.removeEventListener("activated", fileSaveHandler);
}
};
webUIApp.addEventListener("activated", fileSaveHandler);
savePicker.pickSaveFileAndContinue();
} else {
savePicker.pickSaveFileAsync()
.done(saveFile, errorCallback);
}
}
}
require("cordova/exec/proxy").add("Camera",module.exports);

View File

@@ -1,534 +0,0 @@
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Collections.Generic;
using Microsoft.Phone.Tasks;
using System.Runtime.Serialization;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using Microsoft.Phone;
using Microsoft.Xna.Framework.Media;
using System.Diagnostics;
namespace WPCordovaClassLib.Cordova.Commands
{
public class Camera : BaseCommand
{
/// <summary>
/// Return base64 encoded string
/// </summary>
private const int DATA_URL = 0;
/// <summary>
/// Return file uri
/// </summary>
private const int FILE_URI = 1;
/// <summary>
/// Return native uri
/// </summary>
private const int NATIVE_URI = 2;
/// <summary>
/// Choose image from picture library
/// </summary>
private const int PHOTOLIBRARY = 0;
/// <summary>
/// Take picture from camera
/// </summary>
private const int CAMERA = 1;
/// <summary>
/// Choose image from picture library
/// </summary>
private const int SAVEDPHOTOALBUM = 2;
/// <summary>
/// Take a picture of type JPEG
/// </summary>
private const int JPEG = 0;
/// <summary>
/// Take a picture of type PNG
/// </summary>
private const int PNG = 1;
/// <summary>
/// Folder to store captured images
/// </summary>
private const string isoFolder = "CapturedImagesCache";
/// <summary>
/// Represents captureImage action options.
/// </summary>
[DataContract]
public class CameraOptions
{
/// <summary>
/// Source to getPicture from.
/// </summary>
[DataMember(IsRequired = false, Name = "sourceType")]
public int PictureSourceType { get; set; }
/// <summary>
/// Format of image that returned from getPicture.
/// </summary>
[DataMember(IsRequired = false, Name = "destinationType")]
public int DestinationType { get; set; }
/// <summary>
/// Quality of saved image
/// </summary>
[DataMember(IsRequired = false, Name = "quality")]
public int Quality { get; set; }
/// <summary>
/// Controls whether or not the image is also added to the device photo album.
/// </summary>
[DataMember(IsRequired = false, Name = "saveToPhotoAlbum")]
public bool SaveToPhotoAlbum { get; set; }
/// <summary>
/// Ignored
/// </summary>
[DataMember(IsRequired = false, Name = "correctOrientation")]
public bool CorrectOrientation { get; set; }
/// <summary>
/// Ignored
/// </summary>
[DataMember(IsRequired = false, Name = "allowEdit")]
public bool AllowEdit { get; set; }
/// <summary>
/// Height in pixels to scale image
/// </summary>
[DataMember(IsRequired = false, Name = "encodingType")]
public int EncodingType { get; set; }
/// <summary>
/// Height in pixels to scale image
/// </summary>
[DataMember(IsRequired = false, Name = "mediaType")]
public int MediaType { get; set; }
/// <summary>
/// Height in pixels to scale image
/// </summary>
[DataMember(IsRequired = false, Name = "targetHeight")]
public int TargetHeight { get; set; }
/// <summary>
/// Width in pixels to scale image
/// </summary>
[DataMember(IsRequired = false, Name = "targetWidth")]
public int TargetWidth { get; set; }
/// <summary>
/// Creates options object with default parameters
/// </summary>
public CameraOptions()
{
this.SetDefaultValues(new StreamingContext());
}
/// <summary>
/// Initializes default values for class fields.
/// Implemented in separate method because default constructor is not invoked during deserialization.
/// </summary>
/// <param name="context"></param>
[OnDeserializing()]
public void SetDefaultValues(StreamingContext context)
{
PictureSourceType = CAMERA;
DestinationType = FILE_URI;
Quality = 80;
TargetHeight = -1;
TargetWidth = -1;
SaveToPhotoAlbum = false;
CorrectOrientation = true;
AllowEdit = false;
MediaType = -1;
EncodingType = -1;
}
}
/// <summary>
/// Camera options
/// </summary>
CameraOptions cameraOptions;
public void takePicture(string options)
{
try
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
// ["quality", "destinationType", "sourceType", "targetWidth", "targetHeight", "encodingType",
// "mediaType", "allowEdit", "correctOrientation", "saveToPhotoAlbum" ]
cameraOptions = new CameraOptions();
cameraOptions.Quality = int.Parse(args[0]);
cameraOptions.DestinationType = int.Parse(args[1]);
cameraOptions.PictureSourceType = int.Parse(args[2]);
cameraOptions.TargetWidth = int.Parse(args[3]);
cameraOptions.TargetHeight = int.Parse(args[4]);
cameraOptions.EncodingType = int.Parse(args[5]);
cameraOptions.MediaType = int.Parse(args[6]);
cameraOptions.AllowEdit = bool.Parse(args[7]);
cameraOptions.CorrectOrientation = bool.Parse(args[8]);
cameraOptions.SaveToPhotoAlbum = bool.Parse(args[9]);
// a very large number will force the other value to be the bound
if (cameraOptions.TargetWidth > -1 && cameraOptions.TargetHeight == -1)
{
cameraOptions.TargetHeight = 100000;
}
else if (cameraOptions.TargetHeight > -1 && cameraOptions.TargetWidth == -1)
{
cameraOptions.TargetWidth = 100000;
}
}
catch (Exception ex)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
// Api supports FILE_URI, DATA_URL, NATIVE_URI destination types.
// Treat all other destination types as an error.
switch (cameraOptions.DestinationType)
{
case Camera.FILE_URI:
case Camera.DATA_URL:
case Camera.NATIVE_URI:
break;
default:
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Incorrect option: destinationType"));
return;
}
ChooserBase<PhotoResult> chooserTask = null;
if (cameraOptions.PictureSourceType == CAMERA)
{
chooserTask = new CameraCaptureTask();
}
else if ((cameraOptions.PictureSourceType == PHOTOLIBRARY) || (cameraOptions.PictureSourceType == SAVEDPHOTOALBUM))
{
chooserTask = new PhotoChooserTask();
}
// if chooserTask is still null, then PictureSourceType was invalid
if (chooserTask != null)
{
chooserTask.Completed += onTaskCompleted;
chooserTask.Show();
}
else
{
Debug.WriteLine("Unrecognized PictureSourceType :: " + cameraOptions.PictureSourceType.ToString());
DispatchCommandResult(new PluginResult(PluginResult.Status.NO_RESULT));
}
}
public void onTaskCompleted(object sender, PhotoResult e)
{
var task = sender as ChooserBase<PhotoResult>;
if (task != null)
{
task.Completed -= onTaskCompleted;
}
if (e.Error != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR));
return;
}
switch (e.TaskResult)
{
case TaskResult.OK:
try
{
string imagePathOrContent = string.Empty;
// Save image back to media library
// only save to photoalbum if it didn't come from there ...
if (cameraOptions.PictureSourceType == CAMERA && cameraOptions.SaveToPhotoAlbum)
{
MediaLibrary library = new MediaLibrary();
Picture pict = library.SavePicture(e.OriginalFileName, e.ChosenPhoto); // to save to photo-roll ...
}
int newAngle = 0;
// There's bug in Windows Phone 8.1 causing Seek on a DssPhotoStream not working properly.
// https://connect.microsoft.com/VisualStudio/feedback/details/783252
// But a mis-oriented file is better than nothing, so try and catch.
try {
int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto);
switch (orient) {
case ImageExifOrientation.LandscapeLeft:
newAngle = 90;
break;
case ImageExifOrientation.PortraitUpsideDown:
newAngle = 180;
break;
case ImageExifOrientation.LandscapeRight:
newAngle = 270;
break;
case ImageExifOrientation.Portrait:
default: break; // 0 default already set
}
} catch {
Debug.WriteLine("Error fetching orientation from Exif");
}
if (newAngle != 0)
{
using (Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle))
{
// we should reset stream position after saving stream to media library
rotImageStream.Seek(0, SeekOrigin.Begin);
if (cameraOptions.DestinationType == DATA_URL)
{
imagePathOrContent = GetImageContent(rotImageStream);
}
else // FILE_URL or NATIVE_URI (both use the same resultant uri format)
{
imagePathOrContent = SaveImageToLocalStorage(rotImageStream, Path.GetFileName(e.OriginalFileName));
}
}
}
else // no need to reorient
{
if (cameraOptions.DestinationType == DATA_URL)
{
imagePathOrContent = GetImageContent(e.ChosenPhoto);
}
else // FILE_URL or NATIVE_URI (both use the same resultant uri format)
{
imagePathOrContent = SaveImageToLocalStorage(e.ChosenPhoto, Path.GetFileName(e.OriginalFileName));
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent));
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image."));
}
break;
case TaskResult.Cancel:
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection cancelled."));
break;
default:
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection did not complete!"));
break;
}
}
/// <summary>
/// Returns image content in a form of base64 string
/// </summary>
/// <param name="stream">Image stream</param>
/// <returns>Base64 representation of the image</returns>
private string GetImageContent(Stream stream)
{
byte[] imageContent = null;
try
{
// Resize photo and convert to JPEG
imageContent = ResizePhoto(stream);
}
finally
{
stream.Dispose();
}
return Convert.ToBase64String(imageContent);
}
/// <summary>
/// Resize image
/// </summary>
/// <param name="stream">Image stream</param>
/// <returns>resized image</returns>
private byte[] ResizePhoto(Stream stream)
{
//output
byte[] resizedFile;
BitmapImage objBitmap = new BitmapImage();
objBitmap.SetSource(stream);
objBitmap.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap objWB = new WriteableBitmap(objBitmap);
objBitmap.UriSource = null;
// Calculate resultant image size
int width, height;
if (cameraOptions.TargetWidth >= 0 && cameraOptions.TargetHeight >= 0)
{
// Keep proportionally
double ratio = Math.Min(
(double)cameraOptions.TargetWidth / objWB.PixelWidth,
(double)cameraOptions.TargetHeight / objWB.PixelHeight);
width = Convert.ToInt32(ratio * objWB.PixelWidth);
height = Convert.ToInt32(ratio * objWB.PixelHeight);
}
else
{
width = objWB.PixelWidth;
height = objWB.PixelHeight;
}
//Hold the result stream
using (MemoryStream objBitmapStreamResized = new MemoryStream())
{
try
{
// resize the photo with user defined TargetWidth & TargetHeight
Extensions.SaveJpeg(objWB, objBitmapStreamResized, width, height, 0, cameraOptions.Quality);
}
finally
{
//Dispose bitmaps immediately, they are memory expensive
DisposeImage(objBitmap);
DisposeImage(objWB);
GC.Collect();
}
//Convert the resized stream to a byte array.
int streamLength = (int)objBitmapStreamResized.Length;
resizedFile = new Byte[streamLength]; //-1
objBitmapStreamResized.Position = 0;
//for some reason we have to set Position to zero, but we don't have to earlier when we get the bytes from the chosen photo...
objBitmapStreamResized.Read(resizedFile, 0, streamLength);
}
return resizedFile;
}
/// <summary>
/// Util: Dispose a bitmap resource
/// </summary>
/// <param name="image">BitmapSource subclass to dispose</param>
private void DisposeImage(BitmapSource image)
{
if (image != null)
{
try
{
using (var ms = new MemoryStream(new byte[] { 0x0 }))
{
image.SetSource(ms);
}
}
catch (Exception)
{
}
}
}
/// <summary>
/// Saves captured image in isolated storage
/// </summary>
/// <param name="imageFileName">image file name</param>
/// <returns>Image path</returns>
private string SaveImageToLocalStorage(Stream stream, string imageFileName)
{
if (stream == null)
{
throw new ArgumentNullException("imageBytes");
}
try
{
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists(isoFolder))
{
isoFile.CreateDirectory(isoFolder);
}
string filePath = System.IO.Path.Combine("///" + isoFolder + "/", imageFileName);
using (IsolatedStorageFileStream outputStream = isoFile.CreateFile(filePath))
{
BitmapImage objBitmap = new BitmapImage();
objBitmap.SetSource(stream);
objBitmap.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap objWB = new WriteableBitmap(objBitmap);
objBitmap.UriSource = null;
try
{
//use photo's actual width & height if user doesn't provide width & height
if (cameraOptions.TargetWidth < 0 && cameraOptions.TargetHeight < 0)
{
objWB.SaveJpeg(outputStream, objWB.PixelWidth, objWB.PixelHeight, 0, cameraOptions.Quality);
}
else
{
//Resize
//Keep proportionally
double ratio = Math.Min((double)cameraOptions.TargetWidth / objWB.PixelWidth, (double)cameraOptions.TargetHeight / objWB.PixelHeight);
int width = Convert.ToInt32(ratio * objWB.PixelWidth);
int height = Convert.ToInt32(ratio * objWB.PixelHeight);
// resize the photo with user defined TargetWidth & TargetHeight
objWB.SaveJpeg(outputStream, width, height, 0, cameraOptions.Quality);
}
}
finally
{
//Dispose bitmaps immediately, they are memory expensive
DisposeImage(objBitmap);
DisposeImage(objWB);
GC.Collect();
}
}
return new Uri(filePath, UriKind.Relative).ToString();
}
catch (Exception)
{
//TODO: log or do something else
throw;
}
finally
{
stream.Dispose();
}
}
}
}

View File

@@ -37,28 +37,30 @@
- (UIImage*)retrieveImage:(NSDictionary*)info options:(CDVPictureOptions*)options;
- (CDVPluginResult*)resultForImage:(CDVPictureOptions*)options info:(NSDictionary*)info;
- (CDVPluginResult*)resultForVideo:(NSDictionary*)info;
- (NSDictionary*)convertImageMetadata:(NSData*)imageData;
@end
@implementation CameraTest
- (void)setUp {
- (void)setUp
{
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
self.plugin = [[CDVCamera alloc] init];
}
- (void)tearDown {
- (void)tearDown
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void) testPictureOptionsCreate
- (void)testPictureOptionsCreate
{
NSArray* args;
CDVPictureOptions* options;
NSDictionary* popoverOptions;
// No arguments, check whether the defaults are set
args = @[];
@@ -76,14 +78,10 @@
XCTAssertEqual(options.allowsEditing, NO);
XCTAssertEqual(options.correctOrientation, NO);
XCTAssertEqual(options.saveToPhotoAlbum, NO);
XCTAssertEqualObjects(options.popoverOptions, nil);
XCTAssertEqual(options.cameraDirection, (int)UIImagePickerControllerCameraDeviceRear);
XCTAssertEqual(options.popoverSupported, NO);
XCTAssertEqual(options.usesGeolocation, NO);
// Set each argument, check whether they are set. different from defaults
popoverOptions = @{ @"x" : @1, @"y" : @2, @"width" : @3, @"height" : @4 };
args = @[
@(49),
@(DestinationTypeDataUrl),
@@ -95,7 +93,6 @@
@YES,
@YES,
@YES,
popoverOptions,
@(UIImagePickerControllerCameraDeviceFront),
];
@@ -112,22 +109,17 @@
XCTAssertEqual(options.allowsEditing, YES);
XCTAssertEqual(options.correctOrientation, YES);
XCTAssertEqual(options.saveToPhotoAlbum, YES);
XCTAssertEqualObjects(options.popoverOptions, popoverOptions);
XCTAssertEqual(options.cameraDirection, (int)UIImagePickerControllerCameraDeviceFront);
XCTAssertEqual(options.popoverSupported, NO);
XCTAssertEqual(options.usesGeolocation, NO);
}
- (void) testCameraPickerCreate
- (void)testCameraPickerCreate
{
NSDictionary* popoverOptions;
NSArray* args;
CDVPictureOptions* pictureOptions;
CDVCameraPicker* picker;
// Souce is Camera, and image type
popoverOptions = @{ @"x" : @1, @"y" : @2, @"width" : @3, @"height" : @4 };
// Source is Camera, uses always UIImagePickerController
args = @[
@(49),
@(DestinationTypeDataUrl),
@@ -139,7 +131,6 @@
@YES,
@YES,
@YES,
popoverOptions,
@(UIImagePickerControllerCameraDeviceFront),
];
@@ -157,7 +148,7 @@
XCTAssertEqual(picker.cameraDevice, pictureOptions.cameraDirection);
}
// Souce is not Camera, and all media types
// Source is Photo Library, and all media types - On iOS 14+ uses PHPicker, below uses UIImagePickerController
args = @[
@(49),
@@ -170,7 +161,6 @@
@YES,
@YES,
@YES,
popoverOptions,
@(UIImagePickerControllerCameraDeviceFront),
];
@@ -187,7 +177,7 @@
XCTAssertEqualObjects(picker.mediaTypes, [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType]);
}
// Souce is not Camera, and either Image or Movie media type
// Source is Photo Library, and either Image or Movie media type - On iOS 14+ uses PHPicker
args = @[
@(49),
@@ -200,7 +190,6 @@
@YES,
@YES,
@YES,
popoverOptions,
@(UIImagePickerControllerCameraDeviceFront),
];
@@ -218,7 +207,8 @@
}
}
- (UIImage*) createImage:(CGRect)rect orientation:(UIImageOrientation)imageOrientation {
- (UIImage*)createImage:(CGRect)rect orientation:(UIImageOrientation)imageOrientation
{
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
@@ -233,8 +223,8 @@
return image;
}
- (void) testImageScaleCropForSize {
- (void)testImageScaleCropForSize
{
UIImage *sourceImagePortrait, *sourceImageLandscape, *targetImage;
CGSize targetSize = CGSizeZero;
@@ -279,7 +269,8 @@
XCTAssertEqual(targetImage.size.height, targetSize.height);
}
- (void) testImageScaleNoCropForSize {
- (void)testImageScaleNoCropForSize
{
UIImage *sourceImagePortrait, *sourceImageLandscape, *targetImage;
CGSize targetSize = CGSizeZero;
@@ -330,7 +321,8 @@
XCTAssertEqual(targetImage.size.height, targetSize.height);
}
- (void) testImageCorrectedForOrientation {
- (void)testImageCorrectedForOrientation
{
UIImage *sourceImagePortrait, *sourceImageLandscape, *targetImage;
CGSize targetSize = CGSizeZero;
@@ -383,7 +375,7 @@
}
- (void) testRetrieveImage
- (void)testRetrieveImage
{
CDVPictureOptions* pictureOptions = [[CDVPictureOptions alloc] init];
NSDictionary *infoDict1, *infoDict2;
@@ -461,7 +453,7 @@
XCTAssertEqual(resultImage.size.height, scaledImageWithCrop.size.height);
}
- (void) testProcessImage
- (void)testProcessImage
{
CDVPictureOptions* pictureOptions = [[CDVPictureOptions alloc] init];
NSData* resultData;
@@ -508,4 +500,123 @@
// TODO: usesGeolocation is not tested
}
#pragma mark - PHPickerViewController Tests (iOS 14+)
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000 // Always true on XCode12+
- (void)testPHPickerAvailability API_AVAILABLE(ios(14))
{
XCTAssertNotNil([PHPickerViewController class]);
PHPickerConfiguration *config = [[PHPickerConfiguration alloc] init];
XCTAssertNotNil(config);
config.filter = [PHPickerFilter imagesFilter];
XCTAssertNotNil(config.filter);
PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:config];
XCTAssertNotNil(picker);
}
- (void)testPHPickerConfiguration API_AVAILABLE(ios(14))
{
// Test image filter configuration
PHPickerConfiguration *imageConfig = [[PHPickerConfiguration alloc] init];
imageConfig.filter = [PHPickerFilter imagesFilter];
imageConfig.selectionLimit = 1;
XCTAssertNotNil(imageConfig);
XCTAssertEqual(imageConfig.selectionLimit, 1);
// Test video filter configuration
PHPickerConfiguration *videoConfig = [[PHPickerConfiguration alloc] init];
videoConfig.filter = [PHPickerFilter videosFilter];
XCTAssertNotNil(videoConfig.filter);
// Test all media types configuration
PHPickerConfiguration *allConfig = [[PHPickerConfiguration alloc] init];
allConfig.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[
[PHPickerFilter imagesFilter],
[PHPickerFilter videosFilter]
]];
XCTAssertNotNil(allConfig.filter);
}
- (void)testPHPickerDelegateConformance API_AVAILABLE(ios(14))
{
// Test that CDVCamera conforms to PHPickerViewControllerDelegate
XCTAssertTrue([self.plugin conformsToProtocol:@protocol(PHPickerViewControllerDelegate)]);
// Test that the delegate method is implemented
SEL delegateSelector = @selector(picker:didFinishPicking:);
XCTAssertTrue([self.plugin respondsToSelector:delegateSelector]);
}
- (void)testShowPHPickerMethod API_AVAILABLE(ios(14))
{
// Test that showPHPicker method exists
SEL showPHPickerSelector = @selector(showPHPicker:withOptions:);
XCTAssertTrue([self.plugin respondsToSelector:showPHPickerSelector]);
// Test that processPHPickerImage method exists
SEL processSelector = @selector(processPHPickerImage:assetIdentifier:callbackId:options:);
XCTAssertTrue([self.plugin respondsToSelector:processSelector]);
// Test that finalizePHPickerImage method exists
SEL finalizeSelector = @selector(finalizePHPickerImage:metadata:callbackId:options:);
XCTAssertTrue([self.plugin respondsToSelector:finalizeSelector]);
}
#endif
- (void)testConvertImageMetadata
{
// Create a test image
UIImage* testImage = [self createImage:CGRectMake(0, 0, 100, 100) orientation:UIImageOrientationUp];
NSData* imageData = UIImageJPEGRepresentation(testImage, 1.0);
XCTAssertNotNil(imageData);
// Test metadata conversion
NSDictionary* metadata = [self.plugin convertImageMetadata:imageData];
// Metadata may be nil for generated images, but the method should not crash
// Real camera images would have EXIF data
XCTAssertTrue(metadata == nil || [metadata isKindOfClass:[NSDictionary class]]);
}
- (void)testPictureOptionsForPHPicker
{
NSArray* args;
CDVPictureOptions* options;
// Test options configuration for photo library (which would use PHPicker on iOS 14+)
args = @[
@(75),
@(DestinationTypeFileUri),
@(UIImagePickerControllerSourceTypePhotoLibrary),
@(800),
@(600),
@(EncodingTypeJPEG),
@(MediaTypePicture),
@NO,
@YES,
@NO,
[NSNull null],
@(UIImagePickerControllerCameraDeviceRear),
];
CDVInvokedUrlCommand* command = [[CDVInvokedUrlCommand alloc] initWithArguments:args callbackId:@"dummy" className:@"myclassname" methodName:@"mymethodname"];
options = [CDVPictureOptions createFromTakePictureArguments:command];
// Verify options are correctly set for photo library source
XCTAssertEqual(options.sourceType, (int)UIImagePickerControllerSourceTypePhotoLibrary);
XCTAssertEqual([options.quality intValue], 75);
XCTAssertEqual(options.destinationType, (int)DestinationTypeFileUri);
XCTAssertEqual(options.targetSize.width, 800);
XCTAssertEqual(options.targetSize.height, 600);
XCTAssertEqual(options.correctOrientation, YES);
XCTAssertEqual(options.mediaType, (int)MediaTypePicture);
}
@end

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# iOS-Tests für CDVCamera
Sie müssen installieren `node.js` in `Cordova-Ios` zu ziehen.
Installieren Sie Cordova-Ios zum ersten Mal:
npm install
... im aktuellen Ordner.
# Testen von Xcode
1. Starten Sie die Datei `CDVCameraTest.xcworkspace` .
2. Wählen Sie im Dropdown-Schema "CDVCameraLibTests"
3. Klicken Sie und halten Sie auf den `Play` -Button und wählen Sie das `Schraubenschlüssel` -Symbol zum Ausführen der tests
# Tests von der Befehlszeile aus
npm test

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# Pruebas de iOS para CDVCamera
Necesita instalar `node.js` en `Córdoba-ios`.
Primero instalar cordova-ios:
npm install
... en la carpeta actual.
# Prueba de Xcode
1. Iniciar el archivo `CDVCameraTest.xcworkspace` .
2. Elija "CDVCameraLibTests" en el menú de lista desplegable esquema
3. Haga clic y mantenga el botón de `Play` y elegir el icono de `llave inglesa` para ejecutar las pruebas
# Pruebas desde la línea de comandos
npm test

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# Tests d'iOS pour CDVCamera
Vous devez installer `node.js` à `cordova-ios`.
Commencez par installer cordova-ios :
npm install
... dans le dossier actuel.
# Tests de Xcode
1. Lancez le fichier `CDVCameraTest.xcworkspace` .
2. Choisissez « CDVCameraLibTests » dans le menu déroulant de régime
3. Cliquez et maintenez sur la touche `Play` et cliquez sur l'icône de `clé` pour exécuter les tests
# Test de la ligne de commande
npm test

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# Test di iOS per CDVCamera
È necessario installare `node. js` per tirare in `cordova-ios`.
In primo luogo installare cordova-ios:
npm install
... nella cartella corrente.
# Test da Xcode
1. Lanciare il file `CDVCameraTest.xcworkspace` .
2. Scegli "CDVCameraLibTests" dal menu a discesa Schema
3. Fare clic e tenere premuto il pulsante `Play` e scegliere l'icona della `chiave inglese` per eseguire i test
# Test dalla riga di comando
npm test

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# CDVCamera の iOS のテスト
`Node.js` `コルドバ`ios をプルするをインストールする必要があります。.
コルドバ ios をインストールします。
npm install
現在のフォルダーに.
# Xcode からテスト
1. `CDVCameraTest.xcworkspace`ファイルを起動します。
2. スキーム] ドロップダウン メニューから"CDVCameraLibTests"を選択します。
3. クリックし、`再生`ボタンを押し、テストを実行する`レンチ`のアイコンを選択
# コマンドラインからテスト
npm test

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# CDVCamera에 대 한 iOS 테스트
`Node.js` `코르도바` ios에서를 설치 해야.
코르도바-ios를 설치 하는 첫번째는:
npm install
현재 폴더에....
# Xcode에서 테스트
1. `CDVCameraTest.xcworkspace` 파일을 시작 합니다.
2. 구성표 드롭 다운 메뉴에서 "CDVCameraLibTests"를 선택
3. 클릭 하 고 `재생` 버튼에는 테스트를 실행 하려면 `공구 모양` 아이콘을 선택
# 명령줄에서 테스트
npm test

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# iOS testy dla CDVCamera
Musisz zainstalować `node.js` ciągnąć w `cordova-ios`.
Najpierw zainstalować cordova-ios:
npm install
... w folderze bieżącym.
# Badania z Xcode
1. Uruchom plik `CDVCameraTest.xcworkspace` .
2. Wybierz z menu rozwijanego systemu "CDVCameraLibTests"
3. Kliknij i przytrzymaj przycisk `Play` i wybrać ikonę `klucz` do testów
# Badania z wiersza polecenia
npm test

View File

@@ -1,39 +0,0 @@
<!---
license: Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# CDVCamera 的 iOS 測試
您需要安裝`node.js``科爾多瓦 ios`中.
第一次安裝科爾多瓦 ios:
npm install
在當前資料夾中。
# 從 Xcode 測試
1. 啟動`CDVCameraTest.xcworkspace`檔。
2. 從方案下拉式功能表中選擇"CDVCameraLibTests"
3. 按一下並堅持`播放`按鈕,然後選擇要運行的測試的`扳手`圖示
# 從命令列測試
npm test

View File

@@ -8,6 +8,6 @@
"cordova-ios": "*"
},
"scripts": {
"test": "xcodebuild -scheme CordovaLib && xcodebuild test -scheme CDVCameraLibTests -destination 'platform=iOS Simulator,name=iPhone 5'"
"test": "xcodebuild -scheme CordovaLib && xcodebuild test -scheme CDVCameraLibTests -destination 'platform=iOS Simulator,name=iPhone 5s'"
}
}

13
tests/package-lock.json generated Normal file
View File

@@ -0,0 +1,13 @@
{
"name": "cordova-plugin-camera-tests",
"version": "8.0.1-dev",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cordova-plugin-camera-tests",
"version": "8.0.1-dev",
"license": "Apache-2.0"
}
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "cordova-plugin-camera-tests",
"version": "2.4.1-dev",
"version": "9.0.0-dev",
"description": "",
"cordova": {
"id": "cordova-plugin-camera-tests",
@@ -10,5 +10,5 @@
"ecosystem:cordova"
],
"author": "",
"license": "Apache 2.0"
"license": "Apache-2.0"
}

View File

@@ -22,12 +22,10 @@
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:rim="http://www.blackberry.com/ns/widgets"
id="cordova-plugin-camera-tests"
version="2.4.1">
version="9.0.0-dev">
<name>Cordova Camera Plugin Tests</name>
<license>Apache 2.0</license>
<dependency id="cordova-plugin-file-transfer" />
<js-module src="tests.js" name="tests">
</js-module>
</plugin>

View File

@@ -19,43 +19,41 @@
*
*/
/* globals Camera, resolveLocalFileSystemURL, FileEntry, CameraPopoverOptions, FileTransfer, FileUploadOptions, LocalFileSystem, MSApp */
/* jshint jasmine: true */
/* globals Camera, resolveLocalFileSystemURL, FileEntry, LocalFileSystem */
/* eslint-env jasmine */
exports.defineAutoTests = function () {
describe('Camera (navigator.camera)', function () {
it("should exist", function () {
it('should exist', function () {
expect(navigator.camera).toBeDefined();
});
it("should contain a getPicture function", function () {
it('should contain a getPicture function', function () {
expect(navigator.camera.getPicture).toBeDefined();
expect(typeof navigator.camera.getPicture == 'function').toBe(true);
expect(typeof navigator.camera.getPicture === 'function').toBe(true);
});
});
describe('Camera Constants (window.Camera + navigator.camera)', function () {
it("camera.spec.1 window.Camera should exist", function () {
it('camera.spec.1 window.Camera should exist', function () {
expect(window.Camera).toBeDefined();
});
it("camera.spec.2 should contain three DestinationType constants", function () {
it('camera.spec.2 should contain three DestinationType constants', function () {
expect(Camera.DestinationType.DATA_URL).toBe(0);
expect(Camera.DestinationType.FILE_URI).toBe(1);
expect(Camera.DestinationType.NATIVE_URI).toBe(2);
expect(navigator.camera.DestinationType.DATA_URL).toBe(0);
expect(navigator.camera.DestinationType.FILE_URI).toBe(1);
expect(navigator.camera.DestinationType.NATIVE_URI).toBe(2);
});
it("camera.spec.3 should contain two EncodingType constants", function () {
it('camera.spec.3 should contain two EncodingType constants', function () {
expect(Camera.EncodingType.JPEG).toBe(0);
expect(Camera.EncodingType.PNG).toBe(1);
expect(navigator.camera.EncodingType.JPEG).toBe(0);
expect(navigator.camera.EncodingType.PNG).toBe(1);
});
it("camera.spec.4 should contain three MediaType constants", function () {
it('camera.spec.4 should contain three MediaType constants', function () {
expect(Camera.MediaType.PICTURE).toBe(0);
expect(Camera.MediaType.VIDEO).toBe(1);
expect(Camera.MediaType.ALLMEDIA).toBe(2);
@@ -64,7 +62,7 @@ exports.defineAutoTests = function () {
expect(navigator.camera.MediaType.ALLMEDIA).toBe(2);
});
it("camera.spec.5 should contain three PictureSourceType constants", function () {
it('camera.spec.5 should contain three PictureSourceType constants', function () {
expect(Camera.PictureSourceType.PHOTOLIBRARY).toBe(0);
expect(Camera.PictureSourceType.CAMERA).toBe(1);
expect(Camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2);
@@ -75,55 +73,54 @@ exports.defineAutoTests = function () {
});
};
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
exports.defineManualTests = function (contentEl, createActionButton) {
var pictureUrl = null;
var fileObj = null;
var fileEntry = null;
var pageStartTime = +new Date();
let pictureUrl = null;
let fileObj = null;
let fileEntry = null;
const pageStartTime = +new Date();
//default camera options
var camQualityDefault = ['50', 50];
var camDestinationTypeDefault = ['FILE_URI', 1];
var camPictureSourceTypeDefault = ['CAMERA', 1];
var camAllowEditDefault = ['allowEdit', false];
var camEncodingTypeDefault = ['JPEG', 0];
var camMediaTypeDefault = ['mediaType', 0];
var camCorrectOrientationDefault = ['correctOrientation', false];
var camSaveToPhotoAlbumDefault = ['saveToPhotoAlbum', true];
// default camera options
const camQualityDefault = ['50', 50];
const camDestinationTypeDefault = ['FILE_URI', 1];
const camPictureSourceTypeDefault = ['CAMERA', 1];
const camAllowEditDefault = ['allowEdit', false];
const camEncodingTypeDefault = ['JPEG', 0];
const camMediaTypeDefault = ['mediaType', 0];
const camCorrectOrientationDefault = ['correctOrientation', false];
const camSaveToPhotoAlbumDefault = ['saveToPhotoAlbum', true];
function log(value) {
function log (value) {
console.log(value);
document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n';
}
function clearStatus() {
function clearStatus () {
document.getElementById('camera_status').innerHTML = '';
document.getElementById('camera_image').src = 'about:blank';
var canvas = document.getElementById('canvas');
const canvas = document.getElementById('canvas');
canvas.width = canvas.height = 1;
pictureUrl = null;
fileObj = null;
fileEntry = null;
}
function setPicture(url, callback) {
function setPicture (url, callback) {
try {
window.atob(url);
// if we got here it is a base64 string (DATA_URL)
url = "data:image/jpeg;base64," + url;
url = 'data:image/jpeg;base64,' + url;
} catch (e) {
// not DATA_URL
}
log('URL: "' + url.slice(0, 90) + '"');
pictureUrl = url;
var img = document.getElementById('camera_image');
var startTime = new Date();
const img = document.getElementById('camera_image');
const startTime = new Date();
img.src = url;
img.onload = function () {
log('Img size: ' + img.naturalWidth + 'x' + img.naturalHeight);
@@ -134,14 +131,14 @@ exports.defineManualTests = function (contentEl, createActionButton) {
};
}
function onGetPictureError(e) {
function onGetPictureError (e) {
log('Error getting picture: ' + (e.code || e));
}
function getPictureWin(data) {
function getPictureWin (data) {
setPicture(data);
// TODO: Fix resolveLocalFileSystemURI to work with native-uri.
if (pictureUrl.indexOf('file:') === 0 || pictureUrl.indexOf('content:') === 0 || pictureUrl.indexOf('ms-appdata:') === 0 || pictureUrl.indexOf('assets-library:') === 0) {
if (pictureUrl.indexOf('file:') === 0 || pictureUrl.indexOf('content:') === 0) {
resolveLocalFileSystemURL(data, function (e) {
fileEntry = e;
logCallback('resolveLocalFileSystemURL()', true)(e.toURL());
@@ -150,68 +147,43 @@ exports.defineManualTests = function (contentEl, createActionButton) {
} else if (pictureUrl.indexOf('data:image/jpeg;base64') === 0) {
// do nothing
} else {
var path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' ');
const path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' ');
fileEntry = new FileEntry('image_name.png', path);
}
}
function getPicture() {
function getPicture () {
clearStatus();
var options = extractOptions();
const options = extractOptions();
log('Getting picture with options: ' + JSON.stringify(options));
var popoverHandle = navigator.camera.getPicture(getPictureWin, onGetPictureError, options);
// Reposition the popover if the orientation changes.
window.onorientationchange = function () {
var newPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, 0);
popoverHandle.setPosition(newPopoverOptions);
};
navigator.camera.getPicture(getPictureWin, onGetPictureError, options);
}
function uploadImage() {
var ft = new FileTransfer(),
options = new FileUploadOptions();
options.fileKey = "photo";
options.fileName = 'test.jpg';
options.mimeType = "image/jpeg";
ft.onprogress = function (progressEvent) {
console.log('progress: ' + progressEvent.loaded + ' of ' + progressEvent.total);
};
var server = "http://sheltered-retreat-43956.herokuapp.com";
ft.upload(pictureUrl, server + '/upload', win, fail, options);
function win(information_back) {
log('upload complete');
}
function fail(message) {
log('upload failed: ' + JSON.stringify(message));
}
}
function logCallback(apiName, success) {
function logCallback (apiName, success) {
return function () {
log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments)));
};
}
/**
* Select image from library using a NATIVE_URI destination type
* Select image from library
* This calls FileEntry.getMetadata, FileEntry.setMetadata, FileEntry.getParent, FileEntry.file, and FileReader.readAsDataURL.
*/
function readFile() {
function onFileReadAsDataURL(evt) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
function readFile () {
function onFileReadAsDataURL (evt) {
const img = document.getElementById('camera_image');
img.style.visibility = 'visible';
img.style.display = 'block';
img.src = evt.target.result;
log("FileReader.readAsDataURL success");
log('FileReader.readAsDataURL success');
}
function onFileReceived(file) {
function onFileReceived (file) {
log('Got file: ' + JSON.stringify(file));
fileObj = file;
var reader = new FileReader();
/* eslint-disable no-undef */
const reader = new FileReader();
/* eslint-enable no-undef */
reader.onload = function () {
log('FileReader.readAsDataURL() - length = ' + reader.result.length);
};
@@ -228,38 +200,38 @@ exports.defineManualTests = function (contentEl, createActionButton) {
}
}
function getFileInfo() {
function getFileInfo () {
// Test FileEntry API here.
fileEntry.getMetadata(logCallback('FileEntry.getMetadata', true), logCallback('FileEntry.getMetadata', false));
fileEntry.setMetadata(logCallback('FileEntry.setMetadata', true), logCallback('FileEntry.setMetadata', false), { "com.apple.MobileBackup": 1 });
fileEntry.setMetadata(logCallback('FileEntry.setMetadata', true), logCallback('FileEntry.setMetadata', false), { 'com.apple.MobileBackup': 1 });
fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
}
/**
* Copy image from library using a NATIVE_URI destination type
* Copy image from library
* This calls FileEntry.copyTo and FileEntry.moveTo.
*/
function copyImage() {
var onFileSystemReceived = function (fileSystem) {
var destDirEntry = fileSystem.root;
var origName = fileEntry.name;
function copyImage () {
const onFileSystemReceived = function (fileSystem) {
const destDirEntry = fileSystem.root;
const origName = fileEntry.name;
// Test FileEntry API here.
fileEntry.copyTo(destDirEntry, 'copied_file.png', logCallback('FileEntry.copyTo', true), logCallback('FileEntry.copyTo', false));
fileEntry.moveTo(destDirEntry, 'moved_file.png', logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false));
//cleanup
//rename moved file back to original name so other tests can reference image
resolveLocalFileSystemURL(destDirEntry.nativeURL+'moved_file.png', function(fileEntry) {
// cleanup
// rename moved file back to original name so other tests can reference image
resolveLocalFileSystemURL(destDirEntry.nativeURL + 'moved_file.png', function (fileEntry) {
fileEntry.moveTo(destDirEntry, origName, logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false));
console.log('Cleanup: successfully renamed file back to original name');
}, function () {
console.log('Cleanup: failed to rename file back to original name');
});
//remove copied file
resolveLocalFileSystemURL(destDirEntry.nativeURL+'copied_file.png', function(fileEntry) {
// remove copied file
resolveLocalFileSystemURL(destDirEntry.nativeURL + 'copied_file.png', function (fileEntry) {
fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false));
console.log('Cleanup: successfully removed copied file');
}, function () {
@@ -271,17 +243,17 @@ exports.defineManualTests = function (contentEl, createActionButton) {
}
/**
* Write image to library using a NATIVE_URI destination type
* Write image to library
* This calls FileEntry.createWriter, FileWriter.write, and FileWriter.truncate.
*/
function writeImage() {
var onFileWriterReceived = function (fileWriter) {
function writeImage () {
const onFileWriterReceived = function (fileWriter) {
fileWriter.onwrite = logCallback('FileWriter.write', true);
fileWriter.onerror = logCallback('FileWriter.write', false);
fileWriter.write("some text!");
fileWriter.write('some text!');
};
var onFileTruncateWriterReceived = function (fileWriter) {
const onFileTruncateWriterReceived = function (fileWriter) {
fileWriter.onwrite = logCallback('FileWriter.truncate', true);
fileWriter.onerror = logCallback('FileWriter.truncate', false);
fileWriter.truncate(10);
@@ -291,28 +263,28 @@ exports.defineManualTests = function (contentEl, createActionButton) {
fileEntry.createWriter(onFileTruncateWriterReceived, null);
}
function displayImageUsingCanvas() {
var canvas = document.getElementById('canvas');
var img = document.getElementById('camera_image');
var w = img.width;
var h = img.height;
function displayImageUsingCanvas () {
const canvas = document.getElementById('canvas');
const img = document.getElementById('camera_image');
let w = img.width;
let h = img.height;
h = 100 / w * h;
w = 100;
canvas.width = w;
canvas.height = h;
var context = canvas.getContext('2d');
const context = canvas.getContext('2d');
context.drawImage(img, 0, 0, w, h);
}
/**
* Remove image from library using a NATIVE_URI destination type
* Remove image from library
* This calls FileEntry.remove.
*/
function removeImage() {
function removeImage () {
fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false));
}
function testInputTag(inputEl) {
function testInputTag (inputEl) {
clearStatus();
// iOS 6 likes to dead-lock in the onchange context if you
// do any alerts or try to remote-debug.
@@ -321,7 +293,8 @@ exports.defineManualTests = function (contentEl, createActionButton) {
}, 0);
}
function testNativeFile2(inputEl) {
function testNativeFile2 (inputEl) {
/* eslint-disable no-undef */
if (!inputEl.value) {
alert('No file selected.');
return;
@@ -331,9 +304,10 @@ exports.defineManualTests = function (contentEl, createActionButton) {
alert('Got value but no file.');
return;
}
var URLApi = window.URL || window.webkitURL;
/* eslint-enable no-undef */
const URLApi = window.URL || window.webkitURL;
if (URLApi) {
var blobURL = URLApi.createObjectURL(fileObj);
const blobURL = URLApi.createObjectURL(fileObj);
if (blobURL) {
setPicture(blobURL, function () {
URLApi.revokeObjectURL(blobURL);
@@ -346,77 +320,77 @@ exports.defineManualTests = function (contentEl, createActionButton) {
}
}
function extractOptions() {
var els = document.querySelectorAll('#image-options select');
var ret = {};
/*jshint -W084 */
for (var i = 0, el; el = els[i]; ++i) {
var value = el.value;
function extractOptions () {
const els = document.querySelectorAll('#image-options select');
const ret = {};
/* eslint-disable no-cond-assign */
for (let i = 0, el; el = els[i]; ++i) {
let value = el.value;
if (value === '') continue;
value = +value;
if (el.isBool) {
ret[el.getAttribute("name")] = !!value;
ret[el.getAttribute('name')] = !!value;
} else {
ret[el.getAttribute("name")] = value;
ret[el.getAttribute('name')] = value;
}
}
/*jshint +W084 */
/* eslint-enable no-cond-assign */
return ret;
}
function createOptionsEl(name, values, selectionDefault) {
var openDiv = '<div style="display: inline-block">' + name + ': ';
var select = '<select name=' + name + ' id="' + name + '">';
function createOptionsEl (name, values, selectionDefault) {
const openDiv = '<div style="display: inline-block">' + name + ': ';
const select = '<select name=' + name + ' id="' + name + '">';
var defaultOption = '';
let defaultOption = '';
if (selectionDefault === undefined) {
defaultOption = '<option value="">default</option>';
}
var options = '';
if (typeof values == 'boolean') {
values = { 'true': 1, 'false': 0 };
let options = '';
if (typeof values === 'boolean') {
values = { true: 1, false: 0 };
}
for (var k in values) {
var isSelected = '';
for (const k in values) {
let isSelected = '';
if (selectionDefault) {
if (selectionDefault[0] == k) {
if (selectionDefault[0] === k) {
isSelected = 'selected';
}
}
options += '<option value="' + values[k] + '" ' + isSelected + '>' + k + '</option>';
}
var closeDiv = '</select></div>';
const closeDiv = '</select></div>';
return openDiv + select + defaultOption + options + closeDiv;
}
/******************************************************************************/
var info_div = '<h1>Camera</h1>' +
const info_div = '<h1>Camera</h1>' +
'<div id="info">' +
'<b>Status:</b> <div id="camera_status"></div>' +
'img: <img width="100" id="camera_image">' +
'canvas: <canvas id="canvas" width="1" height="1"></canvas>' +
'</div>',
options_div = '<h2>Cordova Camera API Options</h2>' +
'</div>';
const options_div = '<h2>Cordova Camera API Options</h2>' +
'<div id="image-options">' +
createOptionsEl('sourceType', Camera.PictureSourceType, camPictureSourceTypeDefault) +
createOptionsEl('destinationType', Camera.DestinationType, camDestinationTypeDefault) +
createOptionsEl('encodingType', Camera.EncodingType, camEncodingTypeDefault) +
createOptionsEl('mediaType', Camera.MediaType, camMediaTypeDefault) +
createOptionsEl('quality', { '0': 0, '50': 50, '80': 80, '100': 100 }, camQualityDefault) +
createOptionsEl('targetWidth', { '50': 50, '200': 200, '800': 800, '2048': 2048 }) +
createOptionsEl('targetHeight', { '50': 50, '200': 200, '800': 800, '2048': 2048 }) +
createOptionsEl('quality', { 0: 0, 50: 50, 80: 80, 100: 100 }, camQualityDefault) +
createOptionsEl('targetWidth', { 50: 50, 200: 200, 800: 800, 2048: 2048 }) +
createOptionsEl('targetHeight', { 50: 50, 200: 200, 800: 800, 2048: 2048 }) +
createOptionsEl('allowEdit', true, camAllowEditDefault) +
createOptionsEl('correctOrientation', true, camCorrectOrientationDefault) +
createOptionsEl('saveToPhotoAlbum', true, camSaveToPhotoAlbumDefault) +
createOptionsEl('cameraDirection', Camera.Direction) +
'</div>',
getpicture_div = '<div id="getpicture"></div>',
test_procedure = '<h4>Recommended Test Procedure</h4>' +
'</div>';
const getpicture_div = '<div id="getpicture"></div>';
const test_procedure = '<h4>Recommended Test Procedure</h4>' +
'Options not specified should be the default value' +
'<br>Status box should update with image and info whenever an image is taken or selected from library' +
'</p><div style="background:#B0C4DE;border:1px solid #FFA07A;margin:15px 6px 0px;min-width:295px;max-width:97%;padding:4px 0px 2px 10px;min-height:160px;max-height:200px;overflow:auto">' +
@@ -429,14 +403,14 @@ exports.defineManualTests = function (contentEl, createActionButton) {
'</p><li>sourceType=PHOTOLIBRARY<br>mediaType=ALLMEDIA<br>allowEdit=true<br>Should be able to select pics and videos and edit picture if selected</li>' +
'</p><li>sourceType=CAMERA<br>targetWidth & targetHeight=50<br>allowEdit=false<br>Do Get File Metadata test below and take note of size<br>Repeat test but with width and height=800. Size should be significantly larger.</li>' +
'</p><li>quality=0<br>targetWidth & targetHeight=default<br>allowEdit=false<br>Do Get File Metadata test below and take note of size<br>Repeat test but with quality=80. Size should be significantly larger.</li>' +
'</ol></div>',
inputs_div = '<h2>Native File Inputs</h2>' +
'</ol></div>';
const inputs_div = '<h2>Native File Inputs</h2>' +
'For the following tests, status box should update with file selected' +
'</p><div>input type=file <input type="file" class="testInputTag"></div>' +
'<div>capture=camera <input type="file" accept="image/*;capture=camera" class="testInputTag"></div>' +
'<div>capture=camcorder <input type="file" accept="video/*;capture=camcorder" class="testInputTag"></div>' +
'<div>capture=microphone <input type="file" accept="audio/*;capture=microphone" class="testInputTag"></div>',
actions_div = '<h2>Actions</h2>' +
'<div>capture=microphone <input type="file" accept="audio/*;capture=microphone" class="testInputTag"></div>';
const actions_div = '<h2>Actions</h2>' +
'For the following tests, ensure that an image is set in status box' +
'</p><div id="metadata"></div>' +
'Expected result: Get metadata about file selected.<br>Status box will show, along with the metadata, "Call to FileEntry.getMetadata success, Call to FileEntry.setMetadata success, Call to FileEntry.getParent success"' +
@@ -453,23 +427,15 @@ exports.defineManualTests = function (contentEl, createActionButton) {
'</p><div id="remove"></div>' +
'Expected result: Remove image from library.<br>Status box will show "FileEntry.remove success:["OK"]';
// We need to wrap this code due to Windows security restrictions
// see http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences for details
if (window.MSApp && window.MSApp.execUnsafeLocalFunction) {
MSApp.execUnsafeLocalFunction(function() {
contentEl.innerHTML = info_div + options_div + getpicture_div + test_procedure + inputs_div + actions_div;
});
} else {
contentEl.innerHTML = info_div + options_div + getpicture_div + test_procedure + inputs_div + actions_div;
}
contentEl.innerHTML = info_div + options_div + getpicture_div + test_procedure + inputs_div + actions_div;
var elements = document.getElementsByClassName("testInputTag");
var listener = function (e) {
const elements = document.getElementsByClassName('testInputTag');
const listener = function (e) {
testInputTag(e.target);
};
for (var i = 0; i < elements.length; ++i) {
var item = elements[i];
item.addEventListener("change", listener, false);
for (let i = 0; i < elements.length; ++i) {
const item = elements[i];
item.addEventListener('change', listener, false);
}
createActionButton('Get picture', function () {
@@ -496,10 +462,6 @@ exports.defineManualTests = function (contentEl, createActionButton) {
writeImage();
}, 'write');
createActionButton('Upload Image', function () {
uploadImage();
}, 'upload');
createActionButton('Draw Using Canvas', function () {
displayImageUsingCanvas();
}, 'draw_canvas');

52
types/index.d.ts vendored
View File

@@ -36,11 +36,6 @@ interface Camera {
cameraSuccess: (data: string) => void,
cameraError: (message: string) => void,
cameraOptions?: CameraOptions): void;
// Next will work only on iOS
//getPicture(
// cameraSuccess: (data: string) => void,
// cameraError: (message: string) => void,
// cameraOptions?: CameraOptions): CameraPopoverHandle;
}
interface CameraOptions {
@@ -51,8 +46,6 @@ interface CameraOptions {
* Defined in navigator.camera.DestinationType. Default is FILE_URI.
* DATA_URL : 0, Return image as base64-encoded string
* FILE_URI : 1, Return image file URI
* NATIVE_URI : 2 Return image native URI
* (e.g., assets-library:// on iOS or content:// on Android)
*/
destinationType?: number;
/**
@@ -60,7 +53,7 @@ interface CameraOptions {
* Defined in navigator.camera.PictureSourceType. Default is CAMERA.
* PHOTOLIBRARY : 0,
* CAMERA : 1,
* SAVEDPHOTOALBUM : 2
* SAVEDPHOTOALBUM : 2 // same as PHOTOLIBRARY, kept for backward compatibility
*/
sourceType?: number;
/** Allow simple editing of image before selection. */
@@ -102,40 +95,6 @@ interface CameraOptions {
* BACK: 1
*/
cameraDirection?: number;
/** iOS-only options that specify popover location in iPad. Defined in CameraPopoverOptions. */
popoverOptions?: CameraPopoverOptions;
}
/**
* A handle to the popover dialog created by navigator.camera.getPicture. Used on iOS only.
*/
interface CameraPopoverHandle {
/**
* Set the position of the popover.
* @param popoverOptions the CameraPopoverOptions that specify the new position.
*/
setPosition(popoverOptions: CameraPopoverOptions): void;
}
/**
* iOS-only parameters that specify the anchor element location and arrow direction
* of the popover when selecting images from an iPad's library or album.
*/
interface CameraPopoverOptions {
x: number;
y: number;
width: number;
height: number;
/**
* Direction the arrow on the popover should point. Defined in Camera.PopoverArrowDirection
* Matches iOS UIPopoverArrowDirection constants.
* ARROW_UP : 1,
* ARROW_DOWN : 2,
* ARROW_LEFT : 4,
* ARROW_RIGHT : 8,
* ARROW_ANY : 15
*/
arrowDir : number;
}
declare var Camera: {
@@ -143,7 +102,6 @@ declare var Camera: {
DestinationType: {
DATA_URL: number;
FILE_URI: number;
NATIVE_URI: number
}
Direction: {
BACK: number;
@@ -163,12 +121,4 @@ declare var Camera: {
CAMERA: number;
SAVEDPHOTOALBUM: number;
}
// Used only on iOS
PopoverArrowDirection: {
ARROW_UP: number;
ARROW_DOWN: number;
ARROW_LEFT: number;
ARROW_RIGHT: number;
ARROW_ANY: number;
}
};

View File

@@ -19,11 +19,9 @@
*
*/
var argscheck = require('cordova/argscheck'),
exec = require('cordova/exec'),
Camera = require('./Camera');
// XXX: commented out
//CameraPopoverHandle = require('./CameraPopoverHandle');
const argscheck = require('cordova/argscheck');
const exec = require('cordova/exec');
const Camera = require('./Camera');
/**
* @namespace navigator
@@ -32,10 +30,10 @@ var argscheck = require('cordova/argscheck'),
/**
* @exports camera
*/
var cameraExport = {};
const cameraExport = {};
// Tack on the Camera Constants to the base camera plugin.
for (var key in Camera) {
for (const key in Camera) {
cameraExport[key] = Camera[key];
}
@@ -66,14 +64,13 @@ for (var key in Camera) {
* @property {number} [quality=50] - 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.)
* @property {module:Camera.DestinationType} [destinationType=FILE_URI] - Choose the format of the return value.
* @property {module:Camera.PictureSourceType} [sourceType=CAMERA] - Set the source of the picture.
* @property {Boolean} [allowEdit=true] - Allow simple editing of image before selection.
* @property {Boolean} [allowEdit=false] - Allow simple editing of image before selection.
* @property {module:Camera.EncodingType} [encodingType=JPEG] - Choose the returned image file's encoding.
* @property {number} [targetWidth] - Width in pixels to scale image. Must be used with `targetHeight`. Aspect ratio remains constant.
* @property {number} [targetHeight] - Height in pixels to scale image. Must be used with `targetWidth`. Aspect ratio remains constant.
* @property {module:Camera.MediaType} [mediaType=PICTURE] - Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`.
* @property {Boolean} [correctOrientation] - Rotate the image to correct for the orientation of the device during capture.
* @property {Boolean} [saveToPhotoAlbum] - Save the image to the photo album on the device after capture.
* @property {module:CameraPopoverOptions} [popoverOptions] - iOS-only options that specify popover location in iPad.
* @property {module:Camera.Direction} [cameraDirection=BACK] - Choose the camera to use (front- or back-facing).
*/
@@ -114,14 +111,8 @@ for (var key in Camera) {
* __Supported Platforms__
*
* - Android
* - BlackBerry
* - Browser
* - Firefox
* - FireOS
* - iOS
* - Windows
* - WP8
* - Ubuntu
*
* More examples [here](#camera-getPicture-examples). Quirks [here](#camera-getPicture-quirks).
*
@@ -131,30 +122,31 @@ for (var key in Camera) {
* @param {module:camera.onError} errorCallback
* @param {module:camera.CameraOptions} options CameraOptions
*/
cameraExport.getPicture = function(successCallback, errorCallback, options) {
cameraExport.getPicture = function (successCallback, errorCallback, options) {
argscheck.checkArgs('fFO', 'Camera.getPicture', arguments);
options = options || {};
var getValue = argscheck.getValue;
const getValue = argscheck.getValue;
var quality = getValue(options.quality, 50);
var destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
var sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
var targetWidth = getValue(options.targetWidth, -1);
var targetHeight = getValue(options.targetHeight, -1);
var encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
var mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
var allowEdit = !!options.allowEdit;
var correctOrientation = !!options.correctOrientation;
var saveToPhotoAlbum = !!options.saveToPhotoAlbum;
var popoverOptions = getValue(options.popoverOptions, null);
var cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
const quality = getValue(options.quality, 50);
const destinationType = getValue(options.destinationType, Camera.DestinationType.FILE_URI);
const sourceType = getValue(options.sourceType, Camera.PictureSourceType.CAMERA);
const targetWidth = getValue(options.targetWidth, -1);
const targetHeight = getValue(options.targetHeight, -1);
const encodingType = getValue(options.encodingType, Camera.EncodingType.JPEG);
const mediaType = getValue(options.mediaType, Camera.MediaType.PICTURE);
const allowEdit = !!options.allowEdit;
const correctOrientation = !!options.correctOrientation;
const saveToPhotoAlbum = !!options.saveToPhotoAlbum;
const cameraDirection = getValue(options.cameraDirection, Camera.Direction.BACK);
var args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, popoverOptions, cameraDirection];
if (allowEdit) {
console.warn('allowEdit is deprecated. It does not work reliably on all platforms. Utilise a dedicated image editing library instead. allowEdit functionality is scheduled to be removed in a future release.');
}
exec(successCallback, errorCallback, "Camera", "takePicture", args);
// XXX: commented out
//return new CameraPopoverHandle();
const args = [quality, destinationType, sourceType, targetWidth, targetHeight, encodingType,
mediaType, allowEdit, correctOrientation, saveToPhotoAlbum, cameraDirection];
exec(successCallback, errorCallback, 'Camera', 'takePicture', args);
};
/**
@@ -178,8 +170,8 @@ cameraExport.getPicture = function(successCallback, errorCallback, options) {
* alert('Failed because: ' + message);
* }
*/
cameraExport.cleanup = function(successCallback, errorCallback) {
exec(successCallback, errorCallback, "Camera", "cleanup", []);
cameraExport.cleanup = function (successCallback, errorCallback) {
exec(successCallback, errorCallback, 'Camera', 'cleanup', []);
};
module.exports = cameraExport;

Some files were not shown because too many files have changed in this diff Show More