mirror of
https://github.com/apache/cordova-plugin-camera.git
synced 2026-02-03 00:06:46 +08:00
Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af18483d69 | ||
|
|
3581c595d7 | ||
|
|
513bfde49e | ||
|
|
43cb385f0e | ||
|
|
45da410662 | ||
|
|
fcfe642147 | ||
|
|
05da230c2a | ||
|
|
986bf6fd3c | ||
|
|
d84b875c44 | ||
|
|
1ffb14d764 | ||
|
|
e851960910 | ||
|
|
ae22820046 | ||
|
|
fa30a56760 | ||
|
|
5c1394058c | ||
|
|
6dcfa9cf9b | ||
|
|
f3cfadb19e | ||
|
|
e9a834955c | ||
|
|
5b84c38a43 | ||
|
|
af566264ef | ||
|
|
a423e57c8a | ||
|
|
481ff27727 | ||
|
|
599ab31090 | ||
|
|
b3b43b1f3c | ||
|
|
b2403c6076 | ||
|
|
c8c3bf0782 | ||
|
|
f3bc296da8 | ||
|
|
938543c203 | ||
|
|
e316e32808 | ||
|
|
8e1e5c8550 | ||
|
|
d53a7770d9 | ||
|
|
42bf5d2983 | ||
|
|
9064130fce | ||
|
|
6366aeba47 | ||
|
|
dbaa458b7f | ||
|
|
f2eebeed0a | ||
|
|
45a50c448e | ||
|
|
10e0efc503 | ||
|
|
cb7e19311a | ||
|
|
7305c64db0 |
@@ -114,3 +114,36 @@
|
||||
* Removes File plugin dependency from windows8 code.
|
||||
* Use WinJS functionality to resize image instead of File plugin functionality
|
||||
* CB-6127 Updated translations for docs
|
||||
|
||||
### 0.3.2 (Sep 17, 2014)
|
||||
* CB-7551 [Camera][iOS 8] Scaled images show a white line
|
||||
* CB-7558 hasPendingOperation flag in Camera plugin's takePicture should be reversed to fix memory errors
|
||||
* CB-7557 Camera plugin tests is missing a File dependency
|
||||
* CB-7423 do cleanup after copyImage manual test
|
||||
* CB-7471 cordova-plugin-camera documentation translation: cordova-plugin-camera
|
||||
* CB-7413 Resolve 'ms-appdata' URIs with File plugin
|
||||
* Fixed minor bugs with the browser
|
||||
* CB-7433 Adds missing window reference to prevent manual tests failure on Android and iOS
|
||||
* CB-7249 cordova-plugin-camera documentation translation: cordova-plugin-camera
|
||||
* CB-4003 Add config option to not use location information in Camera plugin (and default to not use it)
|
||||
* CB-7461 Geolocation fails in Camera plugin in iOS 8
|
||||
* CB-7378 Use single Proxy for both windows8 and windows.
|
||||
* CB-7378 Adds support for windows platform
|
||||
* CB-7433 Fixes manual tests failure on windows
|
||||
* CB-6958 Get the correct default for "quality" in the test
|
||||
* add documentation for manual tests
|
||||
* CB-7249 cordova-plugin-camera documentation translation: cordova-plugin-camera
|
||||
* CB-4003 Add config option to not use location information in Camera plugin (and default to not use it)
|
||||
* CB-7461 Geolocation fails in Camera plugin in iOS 8
|
||||
* CB-7433 Fixes manual tests failure on windows
|
||||
* CB-7378 Use single Proxy for both windows8 and windows.
|
||||
* CB-7378 Adds support for windows platform
|
||||
* CB-6958 Get the correct default for "quality" in the test
|
||||
* add documentation for manual tests
|
||||
* Updated docs for browser
|
||||
* Added support for the browser
|
||||
* CB-7286 [BlackBerry10] Use getUserMedia if camera card is unavailable
|
||||
* CB-7180 Update Camera plugin to support generic plugin webView UIView (which can be either a UIWebView or WKWebView)
|
||||
* Renamed test dir, added nested plugin.xml
|
||||
* CB-6958 added manual tests
|
||||
* CB-6958 Port camera tests to plugin-test-framework
|
||||
|
||||
@@ -60,12 +60,20 @@ Sie können tun, was Sie wollen, mit dem codierten Bildes oder URI, zum Beispiel
|
||||
* 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.
|
||||
@@ -74,6 +82,10 @@ Amazon Fire OS verwendet Absichten zum Starten von der Kamera-Aktivität auf dem
|
||||
|
||||
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].
|
||||
@@ -141,28 +153,40 @@ Optionale Parameter die Kameraeinstellungen anpassen.
|
||||
|
||||
* **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 Bild als base64-codierte Zeichenfolge FILE_URI: 1, / / Return Image-Datei-URI NATIVE_URI: 2 / / Return image native URI (z. B. Ressourcen-Bibliothek: / / auf iOS oder Inhalte: / / auf Android)};
|
||||
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 = {Fotothek: 0, Kamera: 1, SAVEDPHOTOALBUM: 2};
|
||||
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-codierte Bild PNG: 1 / / Return PNG codiertes Bild};
|
||||
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)*
|
||||
* **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 = {Bild: 0, / / Auswahl der Standbilder nur ermöglichen. STANDARD. Will return format specified via DestinationType
|
||||
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
|
||||
};
|
||||
@@ -176,10 +200,13 @@ Optionale Parameter die Kameraeinstellungen anpassen.
|
||||
|
||||
* **CameraDirection**: Wählen Sie die Kamera (vorn oder hinten-gerichtete) verwenden. Der Standardwert ist zurück. Im Sinne `navigator.camera.Direction` *(Anzahl)*
|
||||
|
||||
Camera.Direction = {zurück: 0, / / die hinten gerichteter Kamera vorne verwenden: 1 / / die nach vorn gerichtete Kamera verwenden};
|
||||
Camera.Direction = {
|
||||
BACK : 0, // Use the back-facing camera
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
|
||||
### Amazon Fire OSQuirks
|
||||
### Amazon Fire OS Macken
|
||||
|
||||
* `cameraDirection`Ergebnisse in einem hinten gerichteter Foto Wert.
|
||||
|
||||
@@ -341,9 +368,15 @@ nur iOS-Parametern, die Anker-Element Lage und Pfeil Richtung der Popover angebe
|
||||
|
||||
* **Höhe**: 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)*
|
||||
* **ArrowDir**: Richtung der Pfeil auf der Popover zeigen sollte. Im Sinne `Camera.PopoverArrowDirection` *(Anzahl)*
|
||||
|
||||
Camera.PopoverArrowDirection = {ARROW_UP: 1, / / entspricht iOS UIPopoverArrowDirection Konstanten ARROW_DOWN: 2, ARROW_LEFT: 4, ARROW_RIGHT: 8, ARROW_ANY: 15};
|
||||
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.
|
||||
|
||||
@@ -60,12 +60,20 @@ Puedes hacer lo que quieras con la imagen codificada o URI, por ejemplo:
|
||||
* Amazon fuego 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.
|
||||
@@ -74,6 +82,10 @@ Amazon fuego OS utiliza los intentos para poner en marcha la actividad de la cá
|
||||
|
||||
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].
|
||||
@@ -181,7 +193,7 @@ Parámetros opcionales para personalizar la configuración de la cámara.
|
||||
|
||||
* **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)*
|
||||
* **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
|
||||
@@ -204,7 +216,7 @@ Parámetros opcionales para personalizar la configuración de la cámara.
|
||||
};
|
||||
|
||||
|
||||
### Amazon fuego OSQuirks
|
||||
### Amazon fuego OS rarezas
|
||||
|
||||
* Cualquier `cameraDirection` valor resultados en una foto orientada hacia atrás.
|
||||
|
||||
@@ -240,7 +252,7 @@ Parámetros opcionales para personalizar la configuración de la cámara.
|
||||
|
||||
* Ignora el `allowEdit` parámetro.
|
||||
|
||||
* Ignora el `PictureSourceType` parámetro (usuario elige en una ventana de diálogo)
|
||||
* Ignora el `PictureSourceType` parámetro (el usuario lo elige en una ventana de diálogo)
|
||||
|
||||
* Ignora el`encodingType`
|
||||
|
||||
@@ -371,7 +383,7 @@ Sólo iOS parámetros que especifican la dirección ancla elemento ubicación y
|
||||
|
||||
* **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)*
|
||||
* **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
|
||||
|
||||
@@ -60,20 +60,32 @@ Vous pouvez faire ce que vous voulez avec l'image encodée ou l'URI, par exemple
|
||||
* 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.
|
||||
|
||||
### Spécificités Android
|
||||
### 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].
|
||||
@@ -87,11 +99,11 @@ Y compris un JavaScript `alert()` dans les deux le rappel fonctions peuvent caus
|
||||
setTimeout(function() {/ / votre code ici!}, 0) ;
|
||||
|
||||
|
||||
### Spécificités Windows Phone 7
|
||||
### 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.
|
||||
|
||||
### Spécificités Tizen
|
||||
### Bizarreries de paciarelli
|
||||
|
||||
Paciarelli prend uniquement en charge un `destinationType` de `Camera.DestinationType.FILE_URI` et un `sourceType` de`Camera.PictureSourceType.PHOTOLIBRARY`.
|
||||
|
||||
@@ -145,14 +157,14 @@ Paramètres optionnels pour personnaliser les réglages de l'appareil.
|
||||
|
||||
### Options
|
||||
|
||||
* **quality** : Qualité de l'image enregistrée, comprise entre 0 et 100, où 100 correspond à la pleine résolution de l'appareil, sans perte liée à la compression. La valeur par défaut est 50. *(Nombre)* (Notez que les informations sur la résolution de la caméra sont indisponibles).
|
||||
* **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, // Retourne l'image sous la forme d'une chaîne encodée en base-64
|
||||
FILE_URI : 1, // Retourne l'URI du fichier image
|
||||
NATIVE_URI : 2 // Retourne l'URI native de l'image (ex. assets-library:// sur iOS ou content:// pour Android)
|
||||
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)
|
||||
};
|
||||
|
||||
|
||||
@@ -165,23 +177,24 @@ Paramètres optionnels pour personnaliser les réglages de l'appareil.
|
||||
};
|
||||
|
||||
|
||||
* **allowEdit**: Autoriser une modification simple de l'image avant sa sélection. *(Boolean)*
|
||||
* **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, // Renvoie l'image au format JPEG
|
||||
PNG : 1 // Renvoie l'image au format PNG
|
||||
JPEG : 0, // Return JPEG encoded image
|
||||
PNG : 1 // Return PNG encoded image
|
||||
};
|
||||
|
||||
|
||||
* **targetWidth**: largeur de sortie en pixels de l'image . Doit être utilisé avec **targetHeight**. Le ratio de l'aspect reste constant. *(Nombre)*
|
||||
* **targetWidth**: largeur en pixels de l'image de l'échelle. Doit être utilisé avec **targetHeight**. Aspect ratio reste constant. *(Nombre)*
|
||||
|
||||
* **targetHeight**: hauteur de sortie en pixels de l'image. Doit être utilisé avec **targetWidth**. 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éfinit le type de média à choisir. Ne fonctionne que quand `PictureSourceType` vaut `PHOTOLIBRARY` ou `SAVEDPHOTOALBUM` . Définie dans `nagivator.camera.MediaType` *(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 = {photo: 0, / / permettre la sélection de photos seulement. PAR DÉFAUT. Will return format specified via DestinationType
|
||||
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
|
||||
};
|
||||
@@ -191,18 +204,21 @@ Paramètres optionnels pour personnaliser les réglages de l'appareil.
|
||||
|
||||
* **saveToPhotoAlbum**: enregistrer l'image sur l'album photo sur l'appareil après la capture. *(Booléen)*
|
||||
|
||||
* **popoverOptions**: options pour iOS uniquement qui spécifient l'emplacement de la boîte de dialogue sur iPad. Définie dans`CameraPopoverOptions`.
|
||||
* **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, // utiliser la caméra arrière FRONT: 1 // utiliser la caméra frontale} ;
|
||||
Camera.Direction = {
|
||||
BACK : 0, // Use the back-facing camera
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
|
||||
### Amazon Fire OSQuirks
|
||||
### Amazon Fire OS Quirks
|
||||
|
||||
* Tout `cameraDirection` résultats dans le back-face photo de valeur.
|
||||
|
||||
* Ignore le paramètre `allowEdit`.
|
||||
* Ignore la `allowEdit` paramètre.
|
||||
|
||||
* `Camera.PictureSourceType.PHOTOLIBRARY`et `Camera.PictureSourceType.SAVEDPHOTOALBUM` les deux affichent le même album photo.
|
||||
|
||||
@@ -216,7 +232,7 @@ Paramètres optionnels pour personnaliser les réglages de l'appareil.
|
||||
|
||||
### BlackBerry 10 Quirks
|
||||
|
||||
* Ignore le paramètre `quality`.
|
||||
* Ignore la `quality` paramètre.
|
||||
|
||||
* Ignore la `allowEdit` paramètre.
|
||||
|
||||
@@ -248,7 +264,7 @@ Paramètres optionnels pour personnaliser les réglages de l'appareil.
|
||||
|
||||
### iOS Quirks
|
||||
|
||||
* Choisir la valeur `quality` en dessous de 50 pour éviter les erreurs de mémoire sur certains appareils.
|
||||
* 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.
|
||||
|
||||
@@ -283,7 +299,7 @@ fonction de rappel onError qui fournit un message d'erreur.
|
||||
|
||||
### Paramètres
|
||||
|
||||
* **message** : le message est fourni par du code natif de l'appareil. *(String)*
|
||||
* **message**: le message est fourni par du code natif de l'appareil. *(String)*
|
||||
|
||||
## cameraSuccess
|
||||
|
||||
@@ -296,7 +312,7 @@ fonction de rappel onSuccess qui fournit les données d'image.
|
||||
|
||||
### Paramètres
|
||||
|
||||
* **imageData**: codage Base64 de l'image, *ou* le fichier image URI, selon `cameraOptions` utilisé. *(String)*
|
||||
* **imageData**: codage Base64 de l'image, *ou* le fichier image URI, selon `cameraOptions` en vigueur. *(String)*
|
||||
|
||||
### Exemple
|
||||
|
||||
@@ -314,7 +330,7 @@ Un handle vers la boîte de dialogue de kangourou créé par`navigator.camera.ge
|
||||
|
||||
### Méthodes
|
||||
|
||||
* **setPosition**: Définit la position de la boite de dialogue.
|
||||
* **setPosition**: définir la position de la kangourou.
|
||||
|
||||
### Plates-formes prises en charge
|
||||
|
||||
@@ -326,7 +342,7 @@ Définir la position de la kangourou.
|
||||
|
||||
**Paramètres**:
|
||||
|
||||
* `cameraPopoverOptions`: l'objet `CameraPopoverOptions` spécifiant la nouvelle position
|
||||
* `cameraPopoverOptions`: la `CameraPopoverOptions` qui spécifie la nouvelle position
|
||||
|
||||
### Exemple
|
||||
|
||||
@@ -352,18 +368,18 @@ iOS uniquement les paramètres qui spécifient la direction ancre élément empl
|
||||
|
||||
### CameraPopoverOptions
|
||||
|
||||
* **x**: coordonnée en x (pixels) de l'élément à l'écran sur lequel accrocher la boite de dialogue. *(Number)*
|
||||
* **x**: coordonnée de pixel de l'élément de l'écran sur lequel ancrer le kangourou x. *(Nombre)*
|
||||
|
||||
* **y**: coordonnée en y (pixels) de l'élément à l'écran sur lequel accrocher la boite de dialogue. *(Number)*
|
||||
* **y**: coordonnée de y pixels de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
|
||||
|
||||
* **width**: largeur en pixels de l'élément à l'écran sur lequel accrocher la boite de dialogue. *(Number)*
|
||||
* **largeur**: largeur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
|
||||
|
||||
* **height**: hauteur en pixels de l'élément à l'écran sur lequel accrocher la boite de dialogue. *(Number)*
|
||||
* **hauteur**: hauteur, en pixels, de l'élément de l'écran sur lequel ancrer le kangourou. *(Nombre)*
|
||||
|
||||
* **arrowDir**: Direction vers laquelle la flèche de la boîte de dialogue doit pointer. Définie dans `Camera.PopoverArrowDirection` *(Number)*
|
||||
* **arrowDir**: Direction de la flèche sur le kangourou doit pointer. Définies dans `Camera.PopoverArrowDirection` *(nombre)*
|
||||
|
||||
Camera.PopoverArrowDirection = {
|
||||
ARROW_UP : 1, // correspondent aux constantes iOS UIPopoverArrowDirection
|
||||
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
|
||||
ARROW_DOWN : 2,
|
||||
ARROW_LEFT : 4,
|
||||
ARROW_RIGHT : 8,
|
||||
|
||||
14
doc/index.md
14
doc/index.md
@@ -78,12 +78,20 @@ than `DATA_URL`.
|
||||
- Amazon Fire OS
|
||||
- Android
|
||||
- BlackBerry 10
|
||||
- Browser
|
||||
- Firefox OS
|
||||
- iOS
|
||||
- Tizen
|
||||
- Windows Phone 7 and 8
|
||||
- Windows 8
|
||||
|
||||
### 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
|
||||
|
||||
Amazon Fire OS uses intents to launch the camera activity on the device to capture
|
||||
@@ -96,6 +104,10 @@ 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 image may not appear when the Cordova activity is restored.
|
||||
|
||||
### Browser Quirks
|
||||
|
||||
Can only return photos as base64-encoded image.
|
||||
|
||||
### Firefox OS Quirks
|
||||
|
||||
Camera plugin is currently implemented using [Web Activities](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
|
||||
@@ -221,7 +233,7 @@ Optional parameters to customize the camera settings.
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
### Amazon Fire OSQuirks
|
||||
### Amazon Fire OS Quirks
|
||||
|
||||
- Any `cameraDirection` value results in a back-facing photo.
|
||||
|
||||
|
||||
@@ -60,12 +60,20 @@ Si può fare quello che vuoi con l'immagine codificata o URI, ad esempio:
|
||||
* 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.
|
||||
@@ -74,6 +82,10 @@ Amazon fuoco OS utilizza intenti a lanciare l'attività della fotocamera sul dis
|
||||
|
||||
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 [Attività Web][2].
|
||||
@@ -141,28 +153,40 @@ Parametri opzionali per personalizzare le impostazioni della fotocamera.
|
||||
|
||||
* **destinationType**: Scegli il formato del valore restituito. Il valore predefinito è FILE_URI. Definito in `navigator.camera.DestinationType` *(numero)*
|
||||
|
||||
Camera.DestinationType = {DATA_URL: 0, / / ritorno di immagine come stringa con codifica base64 FILE_URI: 1, / / ritorno file immagine URI NATIVE_URI: 2 / / ritorno immagine nativa URI (ad esempio, beni-biblioteca: / / su iOS o contenuto: / / su Android)};
|
||||
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, fotocamera: 1, SAVEDPHOTOALBUM: 2};
|
||||
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, / / JPEG restituire codificati immagine PNG: 1 / / ritorno PNG codificato immagine};
|
||||
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)*
|
||||
* **mediaType**: impostare il tipo di supporto per scegliere da. Funziona solo quando `PictureSourceType` è `PHOTOLIBRARY` o `SAVEDPHOTOALBUM` . Definito in `nagivator.camera.MediaType` *(numero)*
|
||||
|
||||
Camera.MediaType = {foto: 0, / / permette la selezione di immagini ancora solo. PER IMPOSTAZIONE PREDEFINITA. Will return format specified via DestinationType
|
||||
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
|
||||
};
|
||||
@@ -176,10 +200,13 @@ Parametri opzionali per personalizzare le impostazioni della fotocamera.
|
||||
|
||||
* **cameraDirection**: scegliere la telecamera da utilizzare (o retro-frontale). Il valore predefinito è tornato. Definito in `navigator.camera.Direction` *(numero)*
|
||||
|
||||
Camera.Direction = {indietro: 0, / / utilizzare la fotocamera posteriore anteriore: 1 / / utilizzare la fotocamera frontale};
|
||||
Camera.Direction = {
|
||||
BACK : 0, // Use the back-facing camera
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
|
||||
### Amazon Fire OSQuirks
|
||||
### Amazon fuoco OS stranezze
|
||||
|
||||
* Qualsiasi `cameraDirection` valore i risultati in una foto di lamatura.
|
||||
|
||||
@@ -341,9 +368,15 @@ iOS solo parametri che specificano l'ancoraggio elemento posizione e freccia dir
|
||||
|
||||
* **altezza**: 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)*
|
||||
* **arrowDir**: direzione dovrebbe puntare la freccia il muffin. Definito in `Camera.PopoverArrowDirection` *(numero)*
|
||||
|
||||
Camera.PopoverArrowDirection = {ARROW_UP: 1, / / corrisponde a iOS UIPopoverArrowDirection costanti ARROW_DOWN: 2, ARROW_LEFT: 4, ARROW_RIGHT: 8, ARROW_ANY: 15};
|
||||
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.
|
||||
|
||||
@@ -60,12 +60,20 @@
|
||||
* アマゾン火 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 イメージをキャプチャするデバイス上のカメラの活動を開始する意図を使用して、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオでは、コルドバの活動が復元されるとき、画像が表示されません。
|
||||
@@ -74,6 +82,10 @@
|
||||
|
||||
アンドロイド、イメージをキャプチャするデバイス上でカメラのアクティビティを開始する意図を使用し、メモリの少ない携帯電話、コルドバ活動が殺されるかもしれない。 このシナリオではコルドバ活動が復元されると、イメージが表示されません。
|
||||
|
||||
### ブラウザーの癖
|
||||
|
||||
Base64 エンコード イメージとして写真を返すのみことができます。
|
||||
|
||||
### Firefox OS 癖
|
||||
|
||||
カメラのプラグインは現在、 [Web アクティビティ][2]を使用して実装されていた.
|
||||
@@ -141,28 +153,40 @@ Tizen のみをサポートしている、 `destinationType` の `Camera.Destina
|
||||
|
||||
* **destinationType**: 戻り値の形式を選択します。既定値は FILE_URI です。定義されている `navigator.camera.DestinationType` *(番号)*
|
||||
|
||||
Camera.DestinationType = {DATA_URL: 0、/base64 エンコード文字列 FILE_URI としてイメージを返す/: 1、//画像ファイル URI NATIVE_URI を返す: 2//戻り画像ネイティブ URI (例えば、資産ライブラリ://iOS またはコンテンツに://アンドロイド)};
|
||||
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 = {フォト ライブラリ: 0, カメラ: 1、SAVEDPHOTOALBUM: 2};
|
||||
Camera.PictureSourceType = {
|
||||
PHOTOLIBRARY : 0,
|
||||
CAMERA : 1,
|
||||
SAVEDPHOTOALBUM : 2
|
||||
};
|
||||
|
||||
|
||||
* **allowEdit**: 単純な選択の前に画像の編集を許可します。*(ブール値)*
|
||||
|
||||
* **encodingType**: 返されるイメージ ファイルのエンコーディングを選択します。デフォルトは JPEG です。定義されている `navigator.camera.EncodingType` *(番号)*
|
||||
|
||||
Camera.EncodingType = {JPEG: 0//戻る JPEG PNG イメージをエンコード: 1/返す PNG イメージをエンコードされた/};
|
||||
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` *(番号)*
|
||||
* **mediaType**: から選択するメディアの種類を設定します。 場合にのみ働きます `PictureSourceType` は `PHOTOLIBRARY` または `SAVEDPHOTOALBUM` 。 定義されている `nagivator.camera.MediaType` *(番号)*
|
||||
|
||||
Camera.MediaType = {画像: 0//静止画のみを選択できます。 既定値です。 Will return format specified via DestinationType
|
||||
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
|
||||
};
|
||||
@@ -176,10 +200,13 @@ Tizen のみをサポートしている、 `destinationType` の `Camera.Destina
|
||||
|
||||
* **cameraDirection**: (前面または背面側) を使用するカメラを選択します。既定値は戻るです。定義されている `navigator.camera.Direction` *(番号)*
|
||||
|
||||
Camera.Direction = {戻る: 0、//後ろ向きカメラ前部を使用: 1/フロントに面したカメラを使用して/};
|
||||
Camera.Direction = {
|
||||
BACK : 0, // Use the back-facing camera
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
|
||||
### アマゾン火 OSQuirks
|
||||
### アマゾン火 OS 癖
|
||||
|
||||
* 任意 `cameraDirection` 背面写真で結果の値します。
|
||||
|
||||
@@ -341,9 +368,15 @@ iOS だけ指定パラメーターをポップ オーバーのアンカー要素
|
||||
|
||||
* **高さ**: ポップ オーバーのアンカーになる上の画面要素のピクセル単位の高さ。*(数)*
|
||||
|
||||
* **arrowDir**: 方向のポップ オーバーで矢印をポイントする必要があります。定義されている `Camera.PopoverArrowDirection` *(番号)*
|
||||
* **arrowDir**: 方向のポップ オーバーで矢印をポイントする必要があります。定義されている `Camera.PopoverArrowDirection` *(番号)*
|
||||
|
||||
Camera.PopoverArrowDirection = {ARROW_UP: 1、/iOS UIPopoverArrowDirection 定数 ARROW_DOWN と一致する/: 2、ARROW_LEFT: 4、ARROW_RIGHT: 8、ARROW_ANY: 15};
|
||||
Camera.PopoverArrowDirection = {
|
||||
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
|
||||
ARROW_DOWN : 2,
|
||||
ARROW_LEFT : 4,
|
||||
ARROW_RIGHT : 8,
|
||||
ARROW_ANY : 15
|
||||
};
|
||||
|
||||
|
||||
矢印の方向と、画面の向きを調整するポップ オーバーのサイズを変更可能性がありますに注意してください。 アンカー要素の位置を指定するときの方向の変化を考慮することを確認します。
|
||||
|
||||
@@ -60,12 +60,20 @@
|
||||
* 아마존 화재 운영 체제
|
||||
* 안 드 로이드
|
||||
* 블랙베리 10
|
||||
* 브라우저
|
||||
* Firefox 운영 체제
|
||||
* iOS
|
||||
* Tizen
|
||||
* Windows Phone 7과 8
|
||||
* 윈도우 8
|
||||
|
||||
### 환경 설정 (iOS)
|
||||
|
||||
* **CameraUsesGeolocation** (boolean, 기본값: false)입니다. 캡처 Jpeg, EXIF 헤더에 지리적 데이터를 true로 설정 합니다. 이 경우 위치 정보 사용 권한에 대 한 요청을 일으킬 것 이다 true로 설정 합니다.
|
||||
|
||||
<preference name="CameraUsesGeolocation" value="false" />
|
||||
|
||||
|
||||
### 아마존 화재 OS 단점
|
||||
|
||||
아마존 화재 OS 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다.
|
||||
@@ -74,6 +82,10 @@
|
||||
|
||||
안 드 로이드 의도 사용 하 여 이미지 캡처 장치에서 카메라 활동을 시작 하 고 낮은 메모리와 휴대 전화에 코르 도우 바 활동 살해 수 있습니다. 코르도바 활동 복원 되 면이 시나리오에서는 이미지가 나타나지 않을 수 있습니다.
|
||||
|
||||
### 브라우저 만지면
|
||||
|
||||
수 base64 인코딩 이미지로 사진을 반환 합니다.
|
||||
|
||||
### 파이어 폭스 OS 단점
|
||||
|
||||
카메라 플러그인은 현재 [웹 활동][2] 를 사용 하 여 구현.
|
||||
@@ -141,28 +153,40 @@ Tizen만 지원 한 `destinationType` 의 `Camera.DestinationType.FILE_URI` 와
|
||||
|
||||
* **destinationType**: 반환 값의 형식을 선택 합니다. 기본값은 FILE_URI입니다. 에 정의 된 `navigator.camera.DestinationType` *(수)*
|
||||
|
||||
Camera.DestinationType = {DATA_URL: 0, / / base64 인코딩된 문자열로 FILE_URI 이미지를 반환: 1, / / 이미지 파일 URI NATIVE_URI 반환: 2 / / 반환 이미지 기본 URI (예를 들어, 자산 라이브러리: / / iOS 또는 콘텐츠: / / 안 드 로이드에)};
|
||||
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, 카메라: 1, SAVEDPHOTOALBUM: 2};
|
||||
Camera.PictureSourceType = {
|
||||
PHOTOLIBRARY : 0,
|
||||
CAMERA : 1,
|
||||
SAVEDPHOTOALBUM : 2
|
||||
};
|
||||
|
||||
|
||||
* **allowEdit**: 선택 하기 전에 이미지의 간단한 편집을 허용 합니다. *(부울)*
|
||||
|
||||
* **encodingType**: 반환 된 이미지 파일의 인코딩을 선택 합니다. 기본값은 JPEG입니다. 에 정의 된 `navigator.camera.EncodingType` *(수)*
|
||||
|
||||
Camera.EncodingType = {JPEG: 0, / / 반환 JPEG로 인코딩된 PNG 이미지: 1 / 반환 PNG 이미지 인코딩 /};
|
||||
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` *(수)*
|
||||
* **mediaType**:에서 선택 미디어 유형을 설정 합니다. 때에 작동 `PictureSourceType` 는 `PHOTOLIBRARY` 또는 `SAVEDPHOTOALBUM` . 에 정의 된 `nagivator.camera.MediaType` *(수)*
|
||||
|
||||
Camera.MediaType = {그림: 0, / / 아직 사진만의 선택을 허용 합니다. 기본입니다. Will return format specified via DestinationType
|
||||
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
|
||||
};
|
||||
@@ -176,10 +200,13 @@ Tizen만 지원 한 `destinationType` 의 `Camera.DestinationType.FILE_URI` 와
|
||||
|
||||
* **cameraDirection**: (앞 이나 뒤로-연결)를 사용 하 여 카메라를 선택 하십시오. 기본값은 다시. 에 정의 된 `navigator.camera.Direction` *(수)*
|
||||
|
||||
Camera.Direction = {다시: 0, / / 앞 뒤 방향 카메라를 사용: 1 / 전면을 향하는 카메라를 사용 하 여 /};
|
||||
Camera.Direction = {
|
||||
BACK : 0, // Use the back-facing camera
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
|
||||
### 아마존 화재 OSQuirks
|
||||
### 아마존 화재 OS 단점
|
||||
|
||||
* 어떤 `cameraDirection` 다시 연결 사진에 결과 값.
|
||||
|
||||
@@ -341,9 +368,15 @@ iOS 전용 매개 변수 iPad의 보관 함 또는 앨범에서 이미지를 선
|
||||
|
||||
* **높이**: 높이 (픽셀)는 popover 앵커는 화면 요소. *(수)*
|
||||
|
||||
* **arrowDir**: 방향 화살표는 popover 가리켜야 합니다. 에 정의 된 `Camera.PopoverArrowDirection` *(수)*
|
||||
* **arrowDir**: 방향 화살표는 popover 가리켜야 합니다. 에 정의 된 `Camera.PopoverArrowDirection` *(수)*
|
||||
|
||||
Camera.PopoverArrowDirection = {ARROW_UP: 1, / / iOS UIPopoverArrowDirection 상수 ARROW_DOWN 일치: 2, ARROW_LEFT: 4, ARROW_RIGHT: 8, ARROW_ANY: 15};
|
||||
Camera.PopoverArrowDirection = {
|
||||
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
|
||||
ARROW_DOWN : 2,
|
||||
ARROW_LEFT : 4,
|
||||
ARROW_RIGHT : 8,
|
||||
ARROW_ANY : 15
|
||||
};
|
||||
|
||||
|
||||
참고는 popover의 크기 조정 화살표 방향 및 화면 방향 변경 될 수 있습니다. 앵커 요소 위치를 지정 하는 경우 방향 변경에 대 한 계정에 있는지 확인 합니다.
|
||||
|
||||
@@ -60,20 +60,32 @@ Z zakodowanym obrazem lub URI możesz zrobić co zechcesz, na przykład:
|
||||
* Amazon ogień OS
|
||||
* Android
|
||||
* Jeżyna 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 takim scenariuszu obrazy mogą nie być wyświetlane po przywróceniu aktywności Cordovy.
|
||||
|
||||
### Android dziwactwach
|
||||
### Android dziwactwa
|
||||
|
||||
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].
|
||||
@@ -93,7 +105,7 @@ Tym JavaScript `alert()` w jednej z wywołania zwrotnego funkcji może powodowa
|
||||
|
||||
Wywoływanie aparat native aplikacji, podczas gdy urządzenie jest podłączone przez Zune nie działa i powoduje błąd wywołania zwrotnego.
|
||||
|
||||
### Tizen dziwactwa
|
||||
### Osobliwości Tizen
|
||||
|
||||
Tizen obsługuje tylko `destinationType` z `Camera.DestinationType.FILE_URI` i `sourceType` z`Camera.PictureSourceType.PHOTOLIBRARY`.
|
||||
|
||||
@@ -147,7 +159,7 @@ Opcjonalne parametry, aby dostosować ustawienia aparatu.
|
||||
|
||||
### 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)* (Należy zauważyć, że informacje o rozdzielczość kamery jest niedostępny).
|
||||
* **jakość**: jakość zapisany obraz, wyrażona jako zakres od 0 do 100, gdzie 100 jest zazwyczaj pełnej rozdzielczości bez utraty z kompresji plików. Wartością domyślną jest 50. *(Liczba)* (Należy zauważyć, że informacje o rozdzielczość kamery jest niedostępny).
|
||||
|
||||
* **destinationType**: Wybierz format zwracanej wartości. Wartością domyślną jest FILE_URI. Zdefiniowane w `navigator.camera.DestinationType` *(numer)*
|
||||
|
||||
@@ -167,7 +179,7 @@ Opcjonalne parametry, aby dostosować ustawienia aparatu.
|
||||
};
|
||||
|
||||
|
||||
* **allowEdit**: Pozwala na prostą edycję obrazu przed zaznaczeniem. *(Boolean)*
|
||||
* **allowEdit**: umożliwia łatwą edycję obrazu przed zaznaczeniem. *(Wartość logiczna)*
|
||||
|
||||
* **encodingType**: Wybierz plik obrazu zwracany jest kodowanie. Domyślnie jest JPEG. Zdefiniowane w `navigator.camera.EncodingType` *(numer)*
|
||||
|
||||
@@ -177,40 +189,40 @@ Opcjonalne parametry, aby dostosować ustawienia aparatu.
|
||||
};
|
||||
|
||||
|
||||
* **targetWidth**: Szerokość w pikselach skalowanego obrazu. Musi być użyte z **targetHeight**. Współczynnik proporcji pozostaje stały. *(Liczba)*
|
||||
* **targetWidth**: szerokość w pikselach na obraz skali. Musi być używany z **targetHeight**. Współczynnik proporcji pozostaje stała. *(Liczba)*
|
||||
|
||||
* **targetHeight**: Wysokość w pikselach skalowanego obrazu. Musi być użyte z **targetWidth**. Współczynnik proporcji pozostaje stały. *(Liczba)*
|
||||
* **targetHeight**: wysokość w pikselach na obraz skali. Musi być używany z **targetWidth**. Współczynnik proporcji pozostaje stała. *(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)*
|
||||
* **mediaType**: zestaw typ nośnika, do wyboru. Działa tylko, gdy `PictureSourceType` jest `PHOTOLIBRARY` lub `SAVEDPHOTOALBUM` . Zdefiniowane w `nagivator.camera.MediaType` *(numer)*
|
||||
|
||||
Camera.MediaType = {
|
||||
PICTURE: 0, // umożliwia wybór tylko zdjęcia. DOMYŚLNIE. Will return format specified via DestinationType
|
||||
PICTURE: 0, // allow selection of still pictures only. DOMYŚLNIE. 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)*
|
||||
* **correctOrientation**: obracanie obrazu dla orientacji urządzenia podczas przechwytywania. *(Wartość logiczna)*
|
||||
|
||||
* **saveToPhotoAlbum**: Po przechwyceniu zapisuje na urządzeniu obraz w albumie na zdjęcia. *(Boolean)*
|
||||
* **saveToPhotoAlbum**: Zapisz obraz do albumu fotograficznego na urządzenie po przechwytywania. *(Wartość logiczna)*
|
||||
|
||||
* **popoverOptions**: Opcja tylko dla platformy iOS, która określa położenie wyskakującego okna na iPadzie. Zdefiniowane w `CameraPopoverOptions`.
|
||||
* **popoverOptions**: tylko do iOS opcje, które określają położenie popover w iPad. 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, // Używa tylnej kamery
|
||||
FRONT : 1 // Używa przedniej kamery
|
||||
BACK : 0, // Use the back-facing camera
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
|
||||
### Amazon ognia OSQuirks
|
||||
### Amazon ogień OS dziwactwa
|
||||
|
||||
* Jakakolwiek wartość w `cameraDirection` skutkuje użyciem tylnej kamery.
|
||||
* Wszelkie `cameraDirection` wartość wyników w zdjęcie tyłu do kierunku jazdy.
|
||||
|
||||
* Parametr `allowEdit` jest ignorowany.
|
||||
* Ignoruje `allowEdit` parametr.
|
||||
|
||||
* Oba parametry `Camera.PictureSourceType.PHOTOLIBRARY` oraz `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlają ten sam album ze zdjęciami.
|
||||
* `Camera.PictureSourceType.PHOTOLIBRARY`i `Camera.PictureSourceType.SAVEDPHOTOALBUM` wyświetlać ten sam album zdjęć.
|
||||
|
||||
### Android dziwactwa
|
||||
|
||||
@@ -222,7 +234,7 @@ Opcjonalne parametry, aby dostosować ustawienia aparatu.
|
||||
|
||||
### Jeżyna 10 dziwactwa
|
||||
|
||||
* Parametr `quality` jest ignorowany.
|
||||
* Ignoruje `quality` parametr.
|
||||
|
||||
* Ignoruje `allowEdit` parametr.
|
||||
|
||||
@@ -254,7 +266,7 @@ Opcjonalne parametry, aby dostosować ustawienia aparatu.
|
||||
|
||||
### iOS dziwactwa
|
||||
|
||||
* Ustaw `quality` poniżej 50 aby uniknąć błędów pamięci na niektórych urządzeniach.
|
||||
* Zestaw `quality` poniżej 50 do uniknięcia błędy pamięci na niektóre urządzenia.
|
||||
|
||||
* Podczas korzystania z `destinationType.FILE_URI` , zdjęcia są zapisywane w katalogu tymczasowego stosowania. Zawartość katalogu tymczasowego stosowania jest usuwany po zakończeniu aplikacji.
|
||||
|
||||
@@ -262,7 +274,7 @@ Opcjonalne parametry, aby dostosować ustawienia aparatu.
|
||||
|
||||
* opcje nie są obsługiwane
|
||||
|
||||
* zawsze zwraca FILE URI
|
||||
* zawsze zwraca identyfikator URI pliku
|
||||
|
||||
### Windows Phone 7 i 8 dziwactwa
|
||||
|
||||
@@ -289,7 +301,7 @@ funkcja wywołania zwrotnego PrzyBłędzie, która zawiera komunikat o błędzie
|
||||
|
||||
### Parametry
|
||||
|
||||
* **message**: Natywny kod komunikatu zapewniany przez urządzenie. *(Ciąg znaków)*
|
||||
* **wiadomość**: wiadomość jest świadczone przez urządzenie w kodzie macierzystym. *(String)*
|
||||
|
||||
## cameraSuccess
|
||||
|
||||
@@ -302,7 +314,7 @@ onSuccess funkcji wywołania zwrotnego, który dostarcza dane obrazu.
|
||||
|
||||
### Parametry
|
||||
|
||||
* **imageData**: Dane obrazu kodowane przy pomocy Base64 *lub* URI pliku obrazu, w zależności od użycia `cameraOptions`. *(Ciąg znaków)*
|
||||
* **imageData**: kodowanie Base64 danych obrazu, *lub* plik obrazu URI, w zależności od `cameraOptions` w życie. *(String)*
|
||||
|
||||
### Przykład
|
||||
|
||||
@@ -320,7 +332,7 @@ Uchwyt do okna dialogowego popover, stworzony przez`navigator.camera.getPicture`
|
||||
|
||||
### Metody
|
||||
|
||||
* **setPosition**: Ustawia pozycję wyskakującego okna.
|
||||
* **setPosition**: Ustaw pozycję popover.
|
||||
|
||||
### Obsługiwane platformy
|
||||
|
||||
@@ -332,7 +344,7 @@ Ustaw pozycję popover.
|
||||
|
||||
**Parametry**:
|
||||
|
||||
* `cameraPopoverOptions`: `CameraPopoverOptions`, która określa nową pozycję
|
||||
* `cameraPopoverOptions`: `CameraPopoverOptions` , określ nowe położenie
|
||||
|
||||
### Przykład
|
||||
|
||||
@@ -363,15 +375,15 @@ tylko do iOS parametrami, które określić kotwicy element lokalizacji i strza
|
||||
|
||||
### CameraPopoverOptions
|
||||
|
||||
* **x**: współrzędna piksela x elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
|
||||
* **x**: x współrzędnych pikseli ekran element na którym kotwica popover. *(Liczba)*
|
||||
|
||||
* **y**: współrzędna piksela y elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
|
||||
* **y**: Współrzędna y pikseli ekran element na którym kotwica popover. *(Liczba)*
|
||||
|
||||
* **width**: szerokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
|
||||
* **szerokość**: szerokość w pikselach, ekran element na którym kotwica popover. *(Liczba)*
|
||||
|
||||
* **height**: wysokość w pikselach elementu ekranu, na którym zakotwiczone jest wyskakujące okno. *(Liczba)*
|
||||
* **wysokość**: wysokość w pikselach elementów ekranu na którym kotwica popover. *(Liczba)*
|
||||
|
||||
* **arrowDir**: Kierunek, który powinna wskazywać strzałka na wyskakującym oknie. Zdefiniowane w `Camera.PopoverArrowDirection` *(Liczba)*
|
||||
* **arrowDir**: kierunek strzałki na popover powinien wskazywać. Zdefiniowane w `Camera.PopoverArrowDirection` *(numer)*
|
||||
|
||||
Camera.PopoverArrowDirection = {
|
||||
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
|
||||
|
||||
137
doc/ru/index.md
137
doc/ru/index.md
@@ -60,38 +60,50 @@
|
||||
* Amazon Fire ОС
|
||||
* Android
|
||||
* BlackBerry 10
|
||||
* Обозреватель
|
||||
* Firefox OS
|
||||
* iOS
|
||||
* Tizen
|
||||
* Windows Phone 7 и 8
|
||||
* Windows 8
|
||||
|
||||
### Особенности Amazon Fire OS
|
||||
### Предпочтения (iOS)
|
||||
|
||||
* **CameraUsesGeolocation** (логическое значение, по умолчанию false). Для захвата изображения JPEG, значение true, чтобы получить данные геопозиционирования в заголовке EXIF. Это вызовет запрос на разрешения геолокации, если задано значение true.
|
||||
|
||||
<preference name="CameraUsesGeolocation" value="false" />
|
||||
|
||||
|
||||
### Amazon Fire OS причуды
|
||||
|
||||
Amazon Fire OS используют намерения для запуска активности камеры на устройстве для съемки фотографий, и на устройствах с низким объемам памяти, активность Cordova может быть завершена. В этом случае изображение может не появиться при восстановлении активности Cordova.
|
||||
|
||||
### Особенности Android
|
||||
### Android причуды
|
||||
|
||||
Android использует намерения начать действие камеры на устройстве для захвата изображения, и на телефонах с низкой памяти, могут быть убиты Cordova деятельность. В этом случае изображение не может появиться, когда Кордова активность восстанавливается.
|
||||
|
||||
### Особенности Firefox OS
|
||||
### Браузер причуды
|
||||
|
||||
Может возвращать только фотографии как изображения в кодировке base64.
|
||||
|
||||
### Firefox OS причуды
|
||||
|
||||
Модуль камеры в настоящее время реализуется с помощью [Веб деятельности][2].
|
||||
|
||||
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
|
||||
|
||||
### Особенности iOS
|
||||
### iOS причуды
|
||||
|
||||
Включая JavaScript `alert()` в любом из обратного вызова функции может вызвать проблемы. Оберните оповещение в `setTimeout()` выбора изображений iOS или пирог полностью закрыть прежде чем отображает оповещения:
|
||||
|
||||
setTimeout(function() {/ / ваши вещи!}, 0);
|
||||
|
||||
|
||||
### Особенности Windows Phone 7
|
||||
### Windows Phone 7 причуды
|
||||
|
||||
Вызов приложения родной камеры, в то время как устройство подключается через Zune не работает и инициирует обратный вызов для ошибки.
|
||||
|
||||
### Особенности Tizen
|
||||
### Причуды Tizen
|
||||
|
||||
Tizen поддерживает только `destinationType` из `Camera.DestinationType.FILE_URI` и `sourceType` из`Camera.PictureSourceType.PHOTOLIBRARY`.
|
||||
|
||||
@@ -145,69 +157,64 @@ Tizen поддерживает только `destinationType` из `Camera.Desti
|
||||
|
||||
### Параметры
|
||||
|
||||
* **quality**: качество сохраняемого изображения, выражается в виде числа в диапазоне от 0 до 100, где 100 является обычно полным изображением без потери качества при сжатии. Значение по умолчанию — 50. *(Число)* (Обратите внимание, что информация о разрешение камеры недоступна.)
|
||||
* **качество**: качество сохраняемого изображения, выражается в виде диапазона 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 или содержание: / / на андроиде)
|
||||
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
|
||||
PHOTOLIBRARY : 0,
|
||||
CAMERA : 1,
|
||||
SAVEDPHOTOALBUM : 2
|
||||
};
|
||||
|
||||
|
||||
* **allowEdit**: позволит редактирование изображения средствами телефона перед окончательным выбором изображения. *(Логический)*
|
||||
* **allowEdit**: позволяют простое редактирование изображения перед выбором. *(Логическое)*
|
||||
|
||||
* **Тип_шифрования**: выберите возвращенный файл в кодировку. Значение по умолчанию — JPEG. Определяется в `navigator.camera.EncodingType` *(число)*
|
||||
|
||||
Camera.EncodingType = {
|
||||
JPEG: 0, // возвращает изображение в формате JPEG
|
||||
PNG: 1 // возвращает рисунок в формате PNG
|
||||
JPEG : 0, // Return JPEG encoded image
|
||||
PNG : 1 // Return PNG encoded image
|
||||
};
|
||||
|
||||
|
||||
* **targetWidth**: ширина изображения в пикселах к которой необходимо осуществить масштабирование. Это значение должно использоваться совместно с **targetHeight**. Пропорции изображения останутся неизменными. *(Число)*
|
||||
* **targetWidth**: ширина до масштаба изображения в пикселях. Должен использоваться с **targetHeight**. Соотношение остается неизменным. *(Число)*
|
||||
|
||||
* **targetHeight**: высота изображения в пикселах к которой необходимо осуществить масштабирование. Это значение должно использоваться совместно с **targetWidth**. Пропорции изображения останутся неизменными. *(Число)*
|
||||
* **targetHeight**: высота до масштаба изображения в пикселях. Должен использоваться с **targetWidth**. Соотношение остается неизменным. *(Число)*
|
||||
|
||||
* **mediaType**: Установите источник получения изображения, из которого надо выбрать изображение. Работает только если `PictureSourceType` равно `PHOTOLIBRARY` или `SAVEDPHOTOALBUM` . Определено в `nagivator.camera.MediaType` *(число)*
|
||||
* **тип носителя**: задать тип носителя, чтобы выбрать из. Работает только если `PictureSourceType` является `PHOTOLIBRARY` или `SAVEDPHOTOALBUM` . Определяется в `nagivator.camera.MediaType` *(число)*
|
||||
|
||||
Camera.MediaType = {
|
||||
PICTURE: 0, / / разрешить выбор только сохраненных изображений. DEFAULT. Will return format specified via DestinationType
|
||||
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**: вращает изображение, чтобы внести исправления к ориентации устройства во время захвата. *(Логический)*
|
||||
* **correctOrientation**: поворот изображения исправить для ориентации устройства во время захвата. *(Логическое)*
|
||||
|
||||
* **saveToPhotoAlbum**: сохранить изображение в фотоальбом на устройстве после захвата. *(Логический)*
|
||||
* **saveToPhotoAlbum**: сохранить изображение в фотоальбом на устройстве после захвата. *(Логическое)*
|
||||
|
||||
* **popoverOptions**: только для iOS параметры, которые определяют местоположение инструмента в iPad. Определены в`CameraPopoverOptions`.
|
||||
|
||||
* **cameraDirection**: выбрать камеру для использования (передней или задней стороне). Значение по умолчанию — обратно. Определяется в `navigator.camera.Direction` *(число)*
|
||||
|
||||
Camera.Direction = {обратно: 0, / / использовать обратно, стоящих перед камерой фронт: 1 / / использовать фронтальная камера};
|
||||
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 причуды
|
||||
### Amazon Fire OS причуды
|
||||
|
||||
* Любой `cameraDirection` значение результатов на задней стороне фотографии.
|
||||
|
||||
@@ -215,7 +222,15 @@ Tizen поддерживает только `destinationType` из `Camera.Desti
|
||||
|
||||
* Оба параметра `Camera.PictureSourceType.PHOTOLIBRARY` и `Camera.PictureSourceType.SAVEDPHOTOALBUM` отображают один и тот же фотоальбом.
|
||||
|
||||
### Особенности BlackBerry 10
|
||||
### Android причуды
|
||||
|
||||
* Любой `cameraDirection` значение результатов на задней стороне фотографии.
|
||||
|
||||
* Игнорирует `allowEdit` параметр.
|
||||
|
||||
* `Camera.PictureSourceType.PHOTOLIBRARY`и `Camera.PictureSourceType.SAVEDPHOTOALBUM` как отображение же фотоальбом.
|
||||
|
||||
### Причуды blackBerry 10
|
||||
|
||||
* Игнорирует `quality` параметр.
|
||||
|
||||
@@ -231,41 +246,41 @@ Tizen поддерживает только `destinationType` из `Camera.Desti
|
||||
|
||||
* Игнорирует `quality` параметр.
|
||||
|
||||
* Значение `Camera.DestinationType` игнорируется и равно `1` (URI для файла изображения)
|
||||
* `Camera.DestinationType`игнорируется и равен `1` (URI файла изображения)
|
||||
|
||||
* Игнорирует параметр `allowEdit`.
|
||||
* Игнорирует `allowEdit` параметр.
|
||||
|
||||
* Игнорирует параметр `PictureSourceType` (пользователь выбирает его в диалоговом окне)
|
||||
* Игнорирует `PictureSourceType` параметр (пользователь выбирает его в диалоговом окне)
|
||||
|
||||
* Игнорирует параметр `encodingType`
|
||||
* Игнорирует`encodingType`
|
||||
|
||||
* Игнорирует `targetWidth` и `targetHeight`
|
||||
* Игнорирует `targetWidth` и`targetHeight`
|
||||
|
||||
* `Camera.MediaType` не поддерживается.
|
||||
* `Camera.MediaType`не поддерживается.
|
||||
|
||||
* Игнорирует параметр `correctOrientation`.
|
||||
* Игнорирует `correctOrientation` параметр.
|
||||
|
||||
* Игнорирует параметр `cameraDirection`.
|
||||
* Игнорирует `cameraDirection` параметр.
|
||||
|
||||
### Особенности iOS
|
||||
### iOS причуды
|
||||
|
||||
* Установите `quality` ниже 50, для того чтобы избежать ошибок памяти на некоторых устройствах.
|
||||
* Задать `quality` ниже 50, чтобы избежать ошибок памяти на некоторых устройствах.
|
||||
|
||||
* При использовании `destinationType.FILE_URI` , фотографии сохраняются во временном каталоге приложения. Содержимое приложения временного каталога удаляется при завершении приложения.
|
||||
|
||||
### Особенности Tizen
|
||||
### Причуды Tizen
|
||||
|
||||
* options, не поддерживается
|
||||
* параметры, не поддерживаемые
|
||||
|
||||
* всегда возвращает URI файла
|
||||
|
||||
### Windows Phone 7 и 8 причуды
|
||||
|
||||
* Игнорирует параметр `allowEdit`.
|
||||
* Игнорирует `allowEdit` параметр.
|
||||
|
||||
* Игнорирует параметр `correctOrientation`.
|
||||
* Игнорирует `correctOrientation` параметр.
|
||||
|
||||
* Игнорирует параметр `cameraDirection`.
|
||||
* Игнорирует `cameraDirection` параметр.
|
||||
|
||||
* Игнорирует `saveToPhotoAlbum` параметр. Важно: Все изображения, снятые камерой wp7/8 cordova API всегда копируются в рулон камеры телефона. В зависимости от параметров пользователя это также может означать, что изображение автоматически загружены на их OneDrive. Потенциально это может означать, что этот образ доступен для более широкой аудитории, чем ваше приложение предназначено. Если этот блокатор для вашего приложения, вам нужно будет осуществить CameraCaptureTask, как описано на сайте msdn: <http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx> вы можете также комментарий или вверх голосование связанный с этим вопрос [отслеживания][3]
|
||||
|
||||
@@ -284,7 +299,7 @@ Tizen поддерживает только `destinationType` из `Camera.Desti
|
||||
|
||||
### Параметры
|
||||
|
||||
* **message**: сообщение об ошибке предоставляемое платформой устройства. *(Строка)*
|
||||
* **сообщение**: сообщение обеспечивается устройства машинного кода. *(Строка)*
|
||||
|
||||
## cameraSuccess
|
||||
|
||||
@@ -297,7 +312,7 @@ onSuccess обратного вызова функция, которая пре
|
||||
|
||||
### Параметры
|
||||
|
||||
* **imageData**: Данные изображения в Base64 кодировке, *или* URI, в зависимости от применяемых параметров `cameraOptions`. *(Строка)*
|
||||
* **imageData**: Base64 кодирование изображения данных, *или* файла изображения URI, в зависимости от `cameraOptions` в силу. *(Строка)*
|
||||
|
||||
### Пример
|
||||
|
||||
@@ -315,7 +330,7 @@ onSuccess обратного вызова функция, которая пре
|
||||
|
||||
### Методы
|
||||
|
||||
* **setPosition**: Задайте положение инструмента выбора изображения.
|
||||
* **setPosition**: установить положение инструмента.
|
||||
|
||||
### Поддерживаемые платформы
|
||||
|
||||
@@ -327,7 +342,7 @@ onSuccess обратного вызова функция, которая пре
|
||||
|
||||
**Параметры**:
|
||||
|
||||
* `cameraPopoverOptions`: Объект `CameraPopoverOptions`, определяющий новое положение
|
||||
* `cameraPopoverOptions`: `CameraPopoverOptions` , укажите новое положение
|
||||
|
||||
### Пример
|
||||
|
||||
@@ -353,17 +368,23 @@ onSuccess обратного вызова функция, которая пре
|
||||
|
||||
### CameraPopoverOptions
|
||||
|
||||
* **x**: x координата в пикселях элемента экрана, на котором закрепить инструмента. *(Число)*
|
||||
* **x**: x координата пикселя элемента экрана, на который для закрепления инструмента. *(Число)*
|
||||
|
||||
* **x**: y координата в пикселях элемента экрана, на котором закрепить инструмента. *(Число)*
|
||||
* **y**: y координата пикселя элемента экрана, на который для закрепления инструмента. *(Число)*
|
||||
|
||||
* **width**: ширина в пикселях элемента экрана, на котором закрепить инструмент выбора изображения. *(Число)*
|
||||
* **Ширина**: ширина в пикселях экрана элемента, на который для закрепления инструмента. *(Число)*
|
||||
|
||||
* **height**: высота в пикселях элемента экрана, на котором закрепить инструмент выбора изображения. *(Число)*
|
||||
* **рост**: высота в пикселях экрана элемента, на который для закрепления инструмента. *(Число)*
|
||||
|
||||
* **arrowDir**: Направление, куда должна указывать стрелка на инструменте. Определено в `Camera.PopoverArrowDirection` *(число)*
|
||||
* **arrowDir**: стрелка на пирог следует указывать направление. Определяется в `Camera.PopoverArrowDirection` *(число)*
|
||||
|
||||
Camera.PopoverArrowDirection = {ARROW_UP: 1, / / матчи iOS UIPopoverArrowDirection константы ARROW_DOWN: 2, ARROW_LEFT: 4, ARROW_RIGHT: 8, ARROW_ANY: 15};
|
||||
Camera.PopoverArrowDirection = {
|
||||
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
|
||||
ARROW_DOWN : 2,
|
||||
ARROW_LEFT : 4,
|
||||
ARROW_RIGHT : 8,
|
||||
ARROW_ANY : 15
|
||||
};
|
||||
|
||||
|
||||
Обратите внимание, что размер инструмента может измениться для регулировки в направлении стрелки и ориентации экрана. Убедитесь в том, что для учета изменения ориентации при указании расположения элемента привязки.
|
||||
|
||||
123
doc/zh/index.md
123
doc/zh/index.md
@@ -60,12 +60,20 @@
|
||||
* 亞馬遜火 OS
|
||||
* Android 系統
|
||||
* 黑莓 10
|
||||
* 火狐瀏覽器作業系統
|
||||
* 瀏覽器
|
||||
* 火狐瀏覽器的作業系統
|
||||
* iOS
|
||||
* Tizen
|
||||
* 泰
|
||||
* Windows Phone 7 和 8
|
||||
* Windows 8
|
||||
|
||||
### 首選項 (iOS)
|
||||
|
||||
* **CameraUsesGeolocation**(布林值,預設值為 false)。 用於捕獲 jpeg 檔,設置為 true,以在 EXIF 頭資訊中獲取地理定位資料。 這將觸發請求的地理位置的許可權,如果設置為 true。
|
||||
|
||||
<preference name="CameraUsesGeolocation" value="false" />
|
||||
|
||||
|
||||
### 亞馬遜火 OS 怪癖
|
||||
|
||||
亞馬遜火 OS 使用意向啟動捕獲圖像,在設備上的相機活動和與低記憶體手機,科爾多瓦活動可能被殺。 在此方案中,可能不會顯示圖像還原科爾多瓦活動時。
|
||||
@@ -74,30 +82,34 @@
|
||||
|
||||
Android 使用意向啟動捕獲圖像,在設備上的相機活動和與低記憶體手機,科爾多瓦活動可能被殺。 在此方案中,可能不會顯示圖像還原科爾多瓦活動時。
|
||||
|
||||
### 瀏覽器的怪癖
|
||||
|
||||
可以只返回照片作為 base64 編碼的圖像。
|
||||
|
||||
### 火狐瀏覽器作業系統的怪癖
|
||||
|
||||
目前使用[Web 活動][2]實現相機外掛程式.
|
||||
觀景窗外掛程式目前實施使用[Web 活動][2].
|
||||
|
||||
[2]: https://hacks.mozilla.org/2013/01/introducing-web-activities/
|
||||
|
||||
### iOS 的怪癖
|
||||
|
||||
包括 JavaScript `alert()` 中任一回檔的函數可能會導致問題。 換行內的警報 `setTimeout()` ,允許 iOS 圖像選取器或彈出要完全關閉之前警報將顯示:
|
||||
包括 JavaScript `alert()` 在任何回呼函數可能會導致問題。 包裝內的警報 `setTimeout()` 允許 iOS 圖像選取器或氣泡框以完全關閉之前,警報將顯示:
|
||||
|
||||
setTimeout(function() {/ / 做你的事!},0) ;
|
||||
|
||||
|
||||
### Windows Phone 7 的怪癖
|
||||
|
||||
調用本機攝像頭應用程式,同時通過 Zune 連接設備不工作,並觸發錯誤回檔。
|
||||
調用本機攝像頭應用程式,而通過 Zune 所連接的設備不能工作,並且觸發錯誤回檔。
|
||||
|
||||
### Tizen 怪癖
|
||||
### 泰怪癖
|
||||
|
||||
Tizen 僅支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `sourceType` 的`Camera.PictureSourceType.PHOTOLIBRARY`.
|
||||
泰僅支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `sourceType` 的`Camera.PictureSourceType.PHOTOLIBRARY`.
|
||||
|
||||
### 示例
|
||||
|
||||
拍一張照片,並檢索它為 base64 編碼的圖像:
|
||||
拍一張照片,並檢索它作為一個 base64 編碼的圖像:
|
||||
|
||||
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
|
||||
destinationType: Camera.DestinationType.DATA_URL
|
||||
@@ -137,49 +149,64 @@ Tizen 僅支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `sou
|
||||
|
||||
### 選項
|
||||
|
||||
* **品質**: 保存的圖像,表示為一系列的 0-100,在 100 哪裡通常全解析度而不會丟失檔的壓縮品質。 預設值為 50。 *(人數)*(請注意相機的解析度有關的資訊是不可用)。
|
||||
* **品質**: 保存的圖像,表示為範圍 0-100,100,是通常全解析度,無損失從檔案壓縮的品質。 預設值為 50。 *(人數)*(請注意相機的解析度有關的資訊是不可用)。
|
||||
|
||||
* **可**: 選擇傳回值的格式。預設值是 FILE_URI。定義在 `navigator.camera.DestinationType` *(人數)*
|
||||
|
||||
Camera.DestinationType = {DATA_URL: 0,/ / 返回圖像作為 base64 編碼字串 FILE_URI: 1,/ / 返回影像檔的 URI NATIVE_URI: 2 / / 返回圖像本機 URI (例如,資產庫: / / 在 iOS 或內容上: / / 在 Android 上)} ;
|
||||
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,相機: 1,SAVEDPHOTOALBUM: 2} ;
|
||||
Camera.PictureSourceType = {
|
||||
PHOTOLIBRARY : 0,
|
||||
CAMERA : 1,
|
||||
SAVEDPHOTOALBUM : 2
|
||||
};
|
||||
|
||||
|
||||
* **allowEdit**: 允許簡單編輯的選擇面前的形象。*(布林)*
|
||||
* **allowEdit**: 允許簡單編輯前選擇圖像。*(布林)*
|
||||
|
||||
* **encodingType**: 選擇返回的影像檔的編碼。預設值為 JPEG。定義在 `navigator.camera.EncodingType` *(人數)*
|
||||
|
||||
Camera.EncodingType = {JPEG: 0,/ / 返回 JPEG 編碼的 PNG 圖像: 1 / / 返回 PNG 編碼的圖像} ;
|
||||
Camera.EncodingType = {
|
||||
JPEG : 0, // Return JPEG encoded image
|
||||
PNG : 1 // Return PNG encoded image
|
||||
};
|
||||
|
||||
|
||||
* **targetWidth**: 以圖元為單位的尺度圖像的寬度。必須與**targetHeight**一起使用。縱橫比保持不變。*(人數)*
|
||||
* **targetWidth**: 向尺度圖像的圖元寬度。必須用**targetHeight**。縱橫比保持不變。*(人數)*
|
||||
|
||||
* **targetHeight**: 以圖元為單位的尺度圖像的高度。必須與**targetWidth**一起使用。縱橫比保持不變。*(人數)*
|
||||
* **targetHeight**: 以圖元為單位向尺度圖像的高度。必須用**targetWidth**。縱橫比保持不變。*(人數)*
|
||||
|
||||
* **媒體類型**: 設置要從選擇媒體的類型。 時才起作用 `PictureSourceType` 是 `PHOTOLIBRARY` 或 `SAVEDPHOTOALBUM` 。 定義在 `nagivator.camera.MediaType` *(人數)*
|
||||
* **媒體類型**: 設置的媒體,從選擇類型。 時才起作用 `PictureSourceType` 是 `PHOTOLIBRARY` 或 `SAVEDPHOTOALBUM` 。 定義在 `nagivator.camera.MediaType` *(人數)*
|
||||
|
||||
Camera.MediaType = {圖片: 0,/ / 允許只仍然圖片的選擇。 預設情況。 Will return format specified via DestinationType
|
||||
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**: 旋轉圖像,期間擷取裝置的方向的正確。*(布林)*
|
||||
* **correctOrientation**: 旋轉圖像,該設備時捕獲的定向的正確。*(布林)*
|
||||
|
||||
* **saveToPhotoAlbum**: 將圖像保存到相冊在設備上捕獲後。*(布林)*
|
||||
|
||||
* **popoverOptions**: 僅限 iOS 在 iPad 中指定彈出位置的選項。在中定義`CameraPopoverOptions`.
|
||||
* **popoverOptions**: 只有 iOS 在 iPad 中指定氣泡框位置的選項。在中定義`CameraPopoverOptions`.
|
||||
|
||||
* **cameraDirection**: 選擇相機以使用 (前面或後面-面向)。預設值是背。定義在 `navigator.camera.Direction` *(人數)*
|
||||
|
||||
Camera.Direction = {回: 0,/ / 使用前面後面攝像頭: 1 / / 使用前置攝像頭} ;
|
||||
Camera.Direction = {
|
||||
BACK : 0, // Use the back-facing camera
|
||||
FRONT : 1 // Use the front-facing camera
|
||||
};
|
||||
|
||||
|
||||
### 亞馬遜火 OSQuirks
|
||||
### 亞馬遜火 OS 怪癖
|
||||
|
||||
* 任何 `cameraDirection` 值回朝的照片中的結果。
|
||||
|
||||
@@ -189,13 +216,13 @@ Tizen 僅支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `sou
|
||||
|
||||
### Android 的怪癖
|
||||
|
||||
* 任何 `cameraDirection` 值回朝的照片中的結果。
|
||||
* 任何 `cameraDirection` 值結果在背面的照片。
|
||||
|
||||
* 忽略 `allowEdit` 參數。
|
||||
|
||||
* `Camera.PictureSourceType.PHOTOLIBRARY`和 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的相冊。
|
||||
* `Camera.PictureSourceType.PHOTOLIBRARY`和 `Camera.PictureSourceType.SAVEDPHOTOALBUM` 都顯示相同的寫真集。
|
||||
|
||||
### 黑莓 10 怪癖
|
||||
### 黑莓 10 的怪癖
|
||||
|
||||
* 忽略 `quality` 參數。
|
||||
|
||||
@@ -219,7 +246,7 @@ Tizen 僅支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `sou
|
||||
|
||||
* 忽略`encodingType`
|
||||
|
||||
* 忽略 `targetWidth` 和`targetHeight`
|
||||
* 忽略了 `targetWidth` 和`targetHeight`
|
||||
|
||||
* `Camera.MediaType`不受支援。
|
||||
|
||||
@@ -233,13 +260,13 @@ Tizen 僅支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `sou
|
||||
|
||||
* 當使用 `destinationType.FILE_URI` ,照片都保存在應用程式的臨時目錄。應用程式結束時,將刪除該應用程式的臨時目錄中的內容。
|
||||
|
||||
### Tizen 怪癖
|
||||
### 泰怪癖
|
||||
|
||||
* 不支援的選項
|
||||
|
||||
* 始終返回一個檔的 URI
|
||||
* 總是返回一個檔的 URI
|
||||
|
||||
### Windows Phone 7 和 8 怪癖
|
||||
### Windows Phone 7 和 8 的怪癖
|
||||
|
||||
* 忽略 `allowEdit` 參數。
|
||||
|
||||
@@ -256,7 +283,7 @@ Tizen 僅支援 `destinationType` 的 `Camera.DestinationType.FILE_URI` 和 `sou
|
||||
|
||||
## CameraError
|
||||
|
||||
onError 回呼函數的函數提供了一條錯誤訊息。
|
||||
onError 的回呼函數提供了一條錯誤訊息。
|
||||
|
||||
function(message) {
|
||||
// Show a helpful message
|
||||
@@ -269,7 +296,7 @@ onError 回呼函數的函數提供了一條錯誤訊息。
|
||||
|
||||
## cameraSuccess
|
||||
|
||||
onSuccess 提供的圖像資料的回呼函數。
|
||||
提供的圖像資料的 onSuccess 回呼函數。
|
||||
|
||||
function(imageData) {
|
||||
// Do something with the image
|
||||
@@ -278,7 +305,7 @@ onSuccess 提供的圖像資料的回呼函數。
|
||||
|
||||
### 參數
|
||||
|
||||
* **把圖像資料**: Base64 編碼的圖像資料,*或*影像檔的 URI,取決於 `cameraOptions` 生效。*(字串)*
|
||||
* **圖像資料**: Base64 編碼進行編碼的圖像資料,*或*影像檔的 URI,取決於 `cameraOptions` 效果。*(字串)*
|
||||
|
||||
### 示例
|
||||
|
||||
@@ -292,11 +319,11 @@ onSuccess 提供的圖像資料的回呼函數。
|
||||
|
||||
## CameraPopoverHandle
|
||||
|
||||
由創建的彈出對話方塊的控制碼`navigator.camera.getPicture`.
|
||||
由創建的氣泡框對話方塊的控制碼`navigator.camera.getPicture`.
|
||||
|
||||
### 方法
|
||||
|
||||
* **setPosition**: 設置彈出的位置。
|
||||
* **setPosition**: 設置氣泡框的位置。
|
||||
|
||||
### 支援的平臺
|
||||
|
||||
@@ -304,7 +331,7 @@ onSuccess 提供的圖像資料的回呼函數。
|
||||
|
||||
### setPosition
|
||||
|
||||
設置彈出的位置。
|
||||
設置氣泡框的位置。
|
||||
|
||||
**參數**:
|
||||
|
||||
@@ -327,38 +354,44 @@ onSuccess 提供的圖像資料的回呼函數。
|
||||
|
||||
## CameraPopoverOptions
|
||||
|
||||
iOS 僅指定彈出的錨元素的位置和箭頭方向,從 iPad 的庫或專輯選擇圖像時的參數。
|
||||
iOS 僅指定氣泡框的錨元素的位置和箭頭方向,從 iPad 庫或專輯選擇圖像時的參數。
|
||||
|
||||
{x: 0,y: 32,寬度: 320,高度: 480,arrowDir: Camera.PopoverArrowDirection.ARROW_ANY} ;
|
||||
|
||||
|
||||
### CameraPopoverOptions
|
||||
|
||||
* **x**: 圖元的 x 座標上的錨定彈出螢幕元素。*(人數)*
|
||||
* **x**: x 螢幕元素到其錨定氣泡框上的圖元座標。*(人數)*
|
||||
|
||||
* **y**: 到其錨定彈出螢幕元素的 y 圖元座標。*(人數)*
|
||||
* **y**: 螢幕元素到其錨定氣泡框上的 y 圖元座標。*(人數)*
|
||||
|
||||
* **寬度**: 寬度以圖元為單位),到其錨定彈出螢幕元素。*(人數)*
|
||||
* **寬度**: 寬度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)*
|
||||
|
||||
* **高度**: 高度以圖元為單位),到其錨定彈出螢幕元素。*(人數)*
|
||||
* **高度**: 高度以圖元為單位),到其錨定氣泡框上的螢幕元素。*(人數)*
|
||||
|
||||
* **arrowDir**: 上彈出的箭頭應指向的方向。定義在 `Camera.PopoverArrowDirection` *(人數)*
|
||||
* **arrowDir**: 氣泡框上的箭頭應指向的方向。定義在 `Camera.PopoverArrowDirection` *(人數)*
|
||||
|
||||
Camera.PopoverArrowDirection = {ARROW_UP: 1,/ / 匹配 iOS UIPopoverArrowDirection 常量 ARROW_DOWN: 2,ARROW_LEFT: 4,ARROW_RIGHT: 8,ARROW_ANY: 15} ;
|
||||
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`.
|
||||
刪除中間打完電話後保留在臨時存儲中的影像檔 `camera.getPicture` 。 只有當適用的價值 `Camera.sourceType` 等於 `Camera.PictureSourceType.CAMERA` 和 `Camera.destinationType` 等於`Camera.DestinationType.FILE_URI`.
|
||||
|
||||
### 支援的平臺
|
||||
|
||||
|
||||
51
plugin.xml
51
plugin.xml
@@ -22,7 +22,7 @@
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:rim="http://www.blackberry.com/ns/widgets"
|
||||
id="org.apache.cordova.camera"
|
||||
version="0.3.1">
|
||||
version="0.3.2">
|
||||
<name>Camera</name>
|
||||
<description>Cordova Camera Plugin</description>
|
||||
<license>Apache 2.0</license>
|
||||
@@ -56,7 +56,7 @@
|
||||
<runs />
|
||||
</js-module>
|
||||
</platform>
|
||||
|
||||
|
||||
<!-- android -->
|
||||
<platform name="android">
|
||||
<config-file target="res/xml/config.xml" parent="/*">
|
||||
@@ -126,6 +126,7 @@
|
||||
<feature name="Camera">
|
||||
<param name="ios-package" value="CDVCamera" />
|
||||
</feature>
|
||||
<preference name="CameraUsesGeolocation" value="false" />
|
||||
</config-file>
|
||||
|
||||
<js-module src="www/ios/CameraPopoverHandle.js" name="CameraPopoverHandle">
|
||||
@@ -143,6 +144,11 @@
|
||||
<framework src="AssetsLibrary.framework" />
|
||||
<framework src="MobileCoreServices.framework" />
|
||||
<framework src="CoreGraphics.framework" />
|
||||
|
||||
<config-file target="*-Info.plist" parent="NSLocationWhenInUseUsageDescription">
|
||||
<string></string>
|
||||
</config-file>
|
||||
|
||||
</platform>
|
||||
|
||||
<!-- blackberry10 -->
|
||||
@@ -153,10 +159,12 @@
|
||||
</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 -->
|
||||
@@ -210,10 +218,47 @@
|
||||
<js-module src="www/CameraPopoverHandle.js" name="CameraPopoverHandle">
|
||||
<clobbers target="CameraPopoverHandle" />
|
||||
</js-module>
|
||||
<js-module src="src/windows8/CameraProxy.js" name="CameraProxy">
|
||||
<js-module src="src/windows/CameraProxy.js" name="CameraProxy">
|
||||
<merges target="" />
|
||||
</js-module>
|
||||
|
||||
</platform>
|
||||
|
||||
<!-- browser -->
|
||||
<platform name="browser">
|
||||
<config-file target="config.xml" parent="/*">
|
||||
<feature name="Camera">
|
||||
<param name="browser-package" value="Camera" />
|
||||
</feature>
|
||||
</config-file>
|
||||
|
||||
<js-module src="src/browser/CameraProxy.js" name="CameraProxy">
|
||||
<runs />
|
||||
</js-module>
|
||||
</platform>
|
||||
|
||||
<!-- windows -->
|
||||
<platform name="windows">
|
||||
<config-file target="package.windows.appxmanifest" parent="/Package/Capabilities">
|
||||
<Capability Name="picturesLibrary" />
|
||||
<DeviceCapability Name="webcam" />
|
||||
</config-file>
|
||||
<config-file target="package.windows80.appxmanifest" parent="/Package/Capabilities">
|
||||
<Capability Name="picturesLibrary" />
|
||||
<DeviceCapability Name="webcam" />
|
||||
</config-file>
|
||||
<config-file target="package.phone.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">
|
||||
<merges target="" />
|
||||
</js-module>
|
||||
</platform>
|
||||
|
||||
|
||||
|
||||
</plugin>
|
||||
|
||||
@@ -27,7 +27,98 @@ var PictureSourceType = {
|
||||
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] === 'org.apache.cordova.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
|
||||
@@ -112,7 +203,11 @@ module.exports = {
|
||||
|
||||
switch(sourceType) {
|
||||
case PictureSourceType.CAMERA:
|
||||
window.qnx.webplatform.getApplication().cards.camera.open("photo", done, cancel, invoked);
|
||||
if (invokeAvailable) {
|
||||
window.qnx.webplatform.getApplication().cards.camera.open("photo", done, cancel, invoked);
|
||||
} else {
|
||||
showCameraDialog(done, cancel, fail);
|
||||
}
|
||||
break;
|
||||
|
||||
case PictureSourceType.PHOTOLIBRARY:
|
||||
|
||||
102
src/browser/CameraProxy.js
Normal file
102
src/browser/CameraProxy.js
Normal file
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
function takePicture(success, error, opts) {
|
||||
if (opts && opts[2] === 1) {
|
||||
capture(success, error);
|
||||
} else {
|
||||
var input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.name = 'files[]';
|
||||
|
||||
input.onchange = function(inputEvent) {
|
||||
var canvas = document.createElement('canvas');
|
||||
|
||||
var reader = new FileReader();
|
||||
reader.onload = function(readerEvent) {
|
||||
input.parentNode.removeChild(input);
|
||||
|
||||
var imageData = readerEvent.target.result;
|
||||
|
||||
return success(imageData.substr(imageData.indexOf(',') + 1));
|
||||
}
|
||||
|
||||
reader.readAsDataURL(inputEvent.target.files[0]);
|
||||
};
|
||||
|
||||
document.body.appendChild(input);
|
||||
}
|
||||
}
|
||||
|
||||
function capture(success, errorCallback) {
|
||||
var localMediaStream;
|
||||
|
||||
var video = document.createElement('video');
|
||||
var button = document.createElement('button');
|
||||
|
||||
video.width = 320;
|
||||
video.height = 240;
|
||||
button.innerHTML = 'Capture!';
|
||||
|
||||
button.onclick = function() {
|
||||
// create a canvas and capture a frame from video stream
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.getContext('2d').drawImage(video, 0, 0, 320, 240);
|
||||
|
||||
// convert image stored in canvas to base64 encoded image
|
||||
var imageData = canvas.toDataURL('img/png');
|
||||
imageData = imageData.replace('data:image/png;base64,', '');
|
||||
|
||||
// stop video stream, remove video and button
|
||||
localMediaStream.stop();
|
||||
video.parentNode.removeChild(video);
|
||||
button.parentNode.removeChild(button);
|
||||
|
||||
return success(imageData);
|
||||
}
|
||||
|
||||
navigator.getUserMedia = navigator.getUserMedia ||
|
||||
navigator.webkitGetUserMedia ||
|
||||
navigator.mozGetUserMedia ||
|
||||
navigator.msGetUserMedia;
|
||||
|
||||
var successCallback = function(stream) {
|
||||
localMediaStream = stream;
|
||||
video.src = window.URL.createObjectURL(localMediaStream);
|
||||
video.play();
|
||||
|
||||
document.body.appendChild(video);
|
||||
document.body.appendChild(button);
|
||||
}
|
||||
|
||||
if (navigator.getUserMedia) {
|
||||
navigator.getUserMedia({video: true, audio: true}, successCallback, errorCallback);
|
||||
} else {
|
||||
alert('Browser does not support camera :(');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
takePicture: takePicture,
|
||||
cleanup: function(){}
|
||||
};
|
||||
|
||||
require("cordova/exec/proxy").add("Camera",module.exports);
|
||||
@@ -55,8 +55,9 @@ typedef NSUInteger CDVMediaType;
|
||||
@property (assign) bool correctOrientation;
|
||||
@property (assign) bool saveToPhotoAlbum;
|
||||
@property (assign) bool cropToSize;
|
||||
@property (strong) UIWebView* webView;
|
||||
@property (strong) UIView* webView;
|
||||
@property (assign) BOOL popoverSupported;
|
||||
@property (assign) BOOL usesGeolocation;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@@ -49,6 +49,13 @@ static NSSet* org_apache_cordova_validArrowDirections;
|
||||
|
||||
@synthesize hasPendingOperation, pickerController, locationManager;
|
||||
|
||||
|
||||
- (BOOL)usesGeolocation
|
||||
{
|
||||
id useGeo = [self.commandDelegate.settings objectForKey:[@"CameraUsesGeolocation" lowercaseString]];
|
||||
return [(NSNumber*)useGeo boolValue];
|
||||
}
|
||||
|
||||
- (BOOL)popoverSupported
|
||||
{
|
||||
return (NSClassFromString(@"UIPopoverController") != nil) &&
|
||||
@@ -75,7 +82,7 @@ static NSSet* org_apache_cordova_validArrowDirections;
|
||||
NSString* callbackId = command.callbackId;
|
||||
NSArray* arguments = command.arguments;
|
||||
|
||||
self.hasPendingOperation = NO;
|
||||
self.hasPendingOperation = YES;
|
||||
|
||||
NSString* sourceTypeString = [arguments objectAtIndex:2];
|
||||
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; // default
|
||||
@@ -121,6 +128,7 @@ static NSSet* org_apache_cordova_validArrowDirections;
|
||||
// we need to capture this state for memory warnings that dealloc this object
|
||||
cameraPicker.webView = self.webView;
|
||||
cameraPicker.popoverSupported = [self popoverSupported];
|
||||
cameraPicker.usesGeolocation = [self usesGeolocation];
|
||||
|
||||
cameraPicker.correctOrientation = [[arguments objectAtIndex:8] boolValue];
|
||||
cameraPicker.saveToPhotoAlbum = [[arguments objectAtIndex:9] boolValue];
|
||||
@@ -153,7 +161,7 @@ static NSSet* org_apache_cordova_validArrowDirections;
|
||||
} else {
|
||||
[self.viewController presentViewController:cameraPicker animated:YES completion:nil];
|
||||
}
|
||||
self.hasPendingOperation = YES;
|
||||
self.hasPendingOperation = NO;
|
||||
}
|
||||
|
||||
- (void)repositionPopover:(CDVInvokedUrlCommand*)command
|
||||
@@ -306,17 +314,22 @@ static NSSet* org_apache_cordova_validArrowDirections;
|
||||
data = UIImageJPEGRepresentation(returnedImage, 1.0);
|
||||
} else {
|
||||
data = UIImageJPEGRepresentation(returnedImage, cameraPicker.quality / 100.0f);
|
||||
|
||||
NSDictionary *controllerMetadata = [info objectForKey:@"UIImagePickerControllerMediaMetadata"];
|
||||
if (controllerMetadata) {
|
||||
self.data = data;
|
||||
self.metadata = [[NSMutableDictionary alloc] init];
|
||||
|
||||
NSMutableDictionary *EXIFDictionary = [[controllerMetadata objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
|
||||
if (EXIFDictionary) [self.metadata setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
|
||||
|
||||
[[self locationManager] startUpdatingLocation];
|
||||
return;
|
||||
|
||||
if (cameraPicker.usesGeolocation) {
|
||||
NSDictionary *controllerMetadata = [info objectForKey:@"UIImagePickerControllerMediaMetadata"];
|
||||
if (controllerMetadata) {
|
||||
self.data = data;
|
||||
self.metadata = [[NSMutableDictionary alloc] init];
|
||||
|
||||
NSMutableDictionary *EXIFDictionary = [[controllerMetadata objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
|
||||
if (EXIFDictionary) [self.metadata setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
|
||||
|
||||
if (IsAtLeastiOSVersion(@"8.0")) {
|
||||
[[self locationManager] performSelector:NSSelectorFromString(@"requestWhenInUseAuthorization") withObject:nil afterDelay:0];
|
||||
}
|
||||
[[self locationManager] startUpdatingLocation];
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -519,6 +532,10 @@ static NSSet* org_apache_cordova_validArrowDirections;
|
||||
scaledSize = CGSizeMake(MIN(width * scaleFactor, targetWidth), MIN(height * scaleFactor, targetHeight));
|
||||
}
|
||||
|
||||
// If the pixels are floats, it causes a white line in iOS8 and probably other versions too
|
||||
scaledSize.width = (int)scaledSize.width;
|
||||
scaledSize.height = (int)scaledSize.height;
|
||||
|
||||
UIGraphicsBeginImageContext(scaledSize); // this will resize
|
||||
|
||||
[sourceImage drawInRect:CGRectMake(0, 0, scaledSize.width, scaledSize.height)];
|
||||
|
||||
441
src/windows/CameraProxy.js
Normal file
441
src/windows/CameraProxy.js
Normal file
@@ -0,0 +1,441 @@
|
||||
/*
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
/*global Windows:true, URL:true */
|
||||
|
||||
|
||||
var cordova = require('cordova'),
|
||||
Camera = require('./Camera');
|
||||
|
||||
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 encodingType = args[5];
|
||||
var targetWidth = args[3];
|
||||
var targetHeight = args[4];
|
||||
var sourceType = args[2];
|
||||
var destinationType = args[1];
|
||||
var mediaType = args[6];
|
||||
var allowCrop = !!args[7];
|
||||
var saveToPhotoAlbum = args[9];
|
||||
var cameraDirection = args[11];
|
||||
|
||||
// resize method :)
|
||||
var resizeImage = function (file) {
|
||||
var tempPhotoFileName = "";
|
||||
if (encodingType == Camera.EncodingType.PNG) {
|
||||
tempPhotoFileName = "camera_cordova_temp_return.png";
|
||||
} else {
|
||||
tempPhotoFileName = "camera_cordova_temp_return.jpg";
|
||||
}
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
|
||||
Windows.Storage.FileIO.readBufferAsync(storageFile).then(function(buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
var imageData = "data:" + file.contentType + ";base64," + strBase64;
|
||||
var image = new Image();
|
||||
image.src = imageData;
|
||||
image.onload = function() {
|
||||
var imageWidth = targetWidth,
|
||||
imageHeight = targetHeight;
|
||||
var canvas = document.createElement('canvas');
|
||||
|
||||
canvas.width = imageWidth;
|
||||
canvas.height = imageHeight;
|
||||
|
||||
canvas.getContext("2d").drawImage(this, 0, 0, imageWidth, imageHeight);
|
||||
|
||||
var fileContent = canvas.toDataURL(file.contentType).split(',')[1];
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
|
||||
storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (storagefile) {
|
||||
var content = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(fileContent);
|
||||
Windows.Storage.FileIO.writeBufferAsync(storagefile, content).then(function () {
|
||||
successCallback("ms-appdata:///local/" + storagefile.name);
|
||||
}, function () {
|
||||
errorCallback("Resize picture error.");
|
||||
});
|
||||
});
|
||||
};
|
||||
});
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder");
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
// because of asynchronous method, so let the successCallback be called in it.
|
||||
var resizeImageBase64 = function (file) {
|
||||
|
||||
Windows.Storage.FileIO.readBufferAsync(file).done( function(buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
var imageData = "data:" + file.contentType + ";base64," + strBase64;
|
||||
|
||||
var image = new Image();
|
||||
image.src = imageData;
|
||||
|
||||
image.onload = function() {
|
||||
var imageWidth = targetWidth,
|
||||
imageHeight = targetHeight;
|
||||
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);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
if (sourceType != Camera.PictureSourceType.CAMERA) {
|
||||
|
||||
// TODO: Add WP8.1 support
|
||||
// WP8.1 doesn't allow to use of pickSingleFileAsync method
|
||||
// see http://msdn.microsoft.com/en-us/library/windows/apps/br207852.aspx for details
|
||||
// replacement of pickSingleFileAsync - pickSingleFileAndContinue method
|
||||
// will take application to suspended state and this require additional logic to wake application up
|
||||
if (navigator.appVersion.indexOf('Windows Phone 8.1') >= 0 ) {
|
||||
errorCallback('Not supported');
|
||||
return;
|
||||
}
|
||||
|
||||
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
|
||||
fileOpenPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
|
||||
if (mediaType == Camera.MediaType.PICTURE) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
|
||||
}
|
||||
else if (mediaType == Camera.MediaType.VIDEO) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll([".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"]);
|
||||
}
|
||||
else {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
|
||||
}
|
||||
|
||||
fileOpenPicker.pickSingleFileAsync().done(function (file) {
|
||||
if (file) {
|
||||
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImage(file);
|
||||
}
|
||||
else {
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
|
||||
successCallback(URL.createObjectURL(storageFile));
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder.");
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(file);
|
||||
} else {
|
||||
Windows.Storage.FileIO.readBufferAsync(file).done(function (buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
successCallback(strBase64);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
errorCallback("User didn't choose a file.");
|
||||
}
|
||||
}, function () {
|
||||
errorCallback("User didn't choose a file.");
|
||||
});
|
||||
|
||||
} else {
|
||||
|
||||
var CaptureNS = Windows.Media.Capture;
|
||||
|
||||
// Check if necessary API available
|
||||
if (!CaptureNS.CameraCaptureUI) {
|
||||
// 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 capturePreview = null,
|
||||
captureCancelButton = null,
|
||||
capture = null,
|
||||
captureSettings = null;
|
||||
|
||||
var createCameraUI = function () {
|
||||
|
||||
// Create fullscreen preview
|
||||
capturePreview = document.createElement("video");
|
||||
|
||||
// z-order style element for capturePreview and captureCancelButton elts
|
||||
// is necessary to avoid overriding by another page elements, -1 sometimes is not enough
|
||||
capturePreview.style.cssText = "position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-order: 999";
|
||||
|
||||
// Create cancel button
|
||||
captureCancelButton = document.createElement("button");
|
||||
captureCancelButton.innerText = "Cancel";
|
||||
captureCancelButton.style.cssText = "position: fixed; right: 0; bottom: 0; display: block; margin: 20px; z-order: 1000";
|
||||
|
||||
capture = new CaptureNS.MediaCapture();
|
||||
|
||||
captureSettings = new CaptureNS.MediaCaptureInitializationSettings();
|
||||
captureSettings.streamingCaptureMode = CaptureNS.StreamingCaptureMode.video;
|
||||
};
|
||||
|
||||
var startCameraPreview = function () {
|
||||
|
||||
// Search for available camera devices
|
||||
// This is necessary to detect which camera (front or back) we should use
|
||||
var expectedPanel = cameraDirection === 1 ? Windows.Devices.Enumeration.Panel.front : Windows.Devices.Enumeration.Panel.back;
|
||||
Windows.Devices.Enumeration.DeviceInformation.findAllAsync(Windows.Devices.Enumeration.DeviceClass.videoCapture)
|
||||
.done(function (devices) {
|
||||
if (devices.length > 0) {
|
||||
devices.forEach(function(currDev) {
|
||||
if (currDev.enclosureLocation.panel && currDev.enclosureLocation.panel == expectedPanel) {
|
||||
captureSettings.videoDeviceId = currDev.id;
|
||||
}
|
||||
});
|
||||
|
||||
capture.initializeAsync(captureSettings).done(function () {
|
||||
// This is necessary since WP8.1 MediaCapture outputs video stream rotated 90 degrees CCW
|
||||
// TODO: This can be not consistent across devices, need additional testing on various devices
|
||||
capture.setPreviewRotation(Windows.Media.Capture.VideoRotation.clockwise90Degrees);
|
||||
// msdn.microsoft.com/en-us/library/windows/apps/hh452807.aspx
|
||||
capturePreview.msZoom = true;
|
||||
capturePreview.src = URL.createObjectURL(capture);
|
||||
capturePreview.play();
|
||||
|
||||
// Insert preview frame and controls into page
|
||||
document.body.appendChild(capturePreview);
|
||||
document.body.appendChild(captureCancelButton);
|
||||
|
||||
// Bind events to controls
|
||||
capturePreview.addEventListener('click', captureAction);
|
||||
captureCancelButton.addEventListener('click', function () {
|
||||
destroyCameraPreview();
|
||||
errorCallback('Cancelled');
|
||||
}, false);
|
||||
}, function (err) {
|
||||
destroyCameraPreview();
|
||||
errorCallback('Camera intitialization error ' + err);
|
||||
});
|
||||
} else {
|
||||
destroyCameraPreview();
|
||||
errorCallback('Camera not found');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
var destroyCameraPreview = function () {
|
||||
capturePreview.pause();
|
||||
capturePreview.src = null;
|
||||
[capturePreview, captureCancelButton].forEach(function(elem) {
|
||||
if (elem /* && elem in document.body.childNodes */) {
|
||||
document.body.removeChild(elem);
|
||||
}
|
||||
});
|
||||
if (capture) {
|
||||
capture.stopRecordAsync();
|
||||
capture = null;
|
||||
}
|
||||
};
|
||||
|
||||
var captureAction = function () {
|
||||
|
||||
var encodingProperties,
|
||||
fileName,
|
||||
generateUniqueCollisionOption = Windows.Storage.CreationCollisionOption.generateUniqueName,
|
||||
tempFolder = Windows.Storage.ApplicationData.current.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, generateUniqueCollisionOption).done(function(capturedFile) {
|
||||
capture.capturePhotoToStorageFileAsync(encodingProperties, capturedFile).done(function() {
|
||||
|
||||
destroyCameraPreview();
|
||||
|
||||
// success callback for capture operation
|
||||
var success = function(capturedfile) {
|
||||
if (destinationType == Camera.DestinationType.FILE_URI || destinationType == Camera.DestinationType.NATIVE_URI) {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImage(capturedfile);
|
||||
} else {
|
||||
capturedfile.copyAsync(Windows.Storage.ApplicationData.current.localFolder, capturedfile.name, generateUniqueCollisionOption).done(function(copiedfile) {
|
||||
successCallback("ms-appdata:///local/" + copiedfile.name);
|
||||
}, errorCallback);
|
||||
}
|
||||
} else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(capturedfile);
|
||||
} else {
|
||||
Windows.Storage.FileIO.readBufferAsync(capturedfile).done(function(buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
capturedfile.deleteAsync().done(function() {
|
||||
successCallback(strBase64);
|
||||
}, function(err) {
|
||||
console.error(err);
|
||||
successCallback(strBase64);
|
||||
});
|
||||
}, errorCallback);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (saveToPhotoAlbum) {
|
||||
capturedFile.copyAsync(Windows.Storage.KnownFolders.picturesLibrary, capturedFile.name, generateUniqueCollisionOption)
|
||||
.done(function() {
|
||||
success(capturedFile);
|
||||
}, errorCallback);
|
||||
} else {
|
||||
success(capturedFile);
|
||||
}
|
||||
|
||||
|
||||
}, function(err) {
|
||||
destroyCameraPreview();
|
||||
errorCallback(err);
|
||||
});
|
||||
}, function(err) {
|
||||
destroyCameraPreview();
|
||||
errorCallback(err);
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
createCameraUI();
|
||||
startCameraPreview();
|
||||
} catch (ex) {
|
||||
errorCallback(ex);
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
var cameraCaptureUI = new Windows.Media.Capture.CameraCaptureUI();
|
||||
cameraCaptureUI.photoSettings.allowCropping = allowCrop;
|
||||
|
||||
if (encodingType == Camera.EncodingType.PNG) {
|
||||
cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.png;
|
||||
} else {
|
||||
cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.jpeg;
|
||||
}
|
||||
|
||||
// decide which max pixels should be supported by targetWidth or targetHeight.
|
||||
if (targetWidth >= 1280 || targetHeight >= 960) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.large3M;
|
||||
} else if (targetWidth >= 1024 || targetHeight >= 768) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
|
||||
} else if (targetWidth >= 800 || targetHeight >= 600) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
|
||||
} else if (targetWidth >= 640 || targetHeight >= 480) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.smallVga;
|
||||
} else if (targetWidth >= 320 || targetHeight >= 240) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.verySmallQvga;
|
||||
} else {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.highestAvailable;
|
||||
}
|
||||
|
||||
cameraCaptureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function(picture) {
|
||||
if (picture) {
|
||||
// save to photo album successCallback
|
||||
var success = function() {
|
||||
if (destinationType == Camera.DestinationType.FILE_URI) {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImage(picture);
|
||||
} else {
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
picture.copyAsync(storageFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function(storageFile) {
|
||||
successCallback("ms-appdata:///local/" + storageFile.name);
|
||||
}, function() {
|
||||
errorCallback("Can't access localStorage folder.");
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(picture);
|
||||
} else {
|
||||
Windows.Storage.FileIO.readBufferAsync(picture).done(function(buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
successCallback(strBase64);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
// save to photo album errorCallback
|
||||
var fail = function() {
|
||||
//errorCallback("FileError, code:" + fileError.code);
|
||||
errorCallback("Save fail.");
|
||||
};
|
||||
|
||||
if (saveToPhotoAlbum) {
|
||||
Windows.Storage.StorageFile.getFileFromPathAsync(picture.path).then(function(storageFile) {
|
||||
storageFile.copyAsync(Windows.Storage.KnownFolders.picturesLibrary, picture.name, Windows.Storage.NameCollisionOption.generateUniqueName).then(function(storageFile) {
|
||||
success();
|
||||
}, function() {
|
||||
fail();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
success();
|
||||
}
|
||||
} else {
|
||||
errorCallback("User didn't capture a photo.");
|
||||
}
|
||||
}, function() {
|
||||
errorCallback("Fail to capture a photo.");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
require("cordova/exec/proxy").add("Camera",module.exports);
|
||||
@@ -1,292 +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.
|
||||
*
|
||||
*/
|
||||
|
||||
/*global Windows:true, URL:true */
|
||||
|
||||
|
||||
var cordova = require('cordova'),
|
||||
Camera = require('./Camera');
|
||||
|
||||
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
|
||||
|
||||
takePicture: function (successCallback, errorCallback, args) {
|
||||
var encodingType = args[5];
|
||||
var targetWidth = args[3];
|
||||
var targetHeight = args[4];
|
||||
var sourceType = args[2];
|
||||
var destinationType = args[1];
|
||||
var mediaType = args[6];
|
||||
var saveToPhotoAlbum = args[9];
|
||||
|
||||
// resize method :)
|
||||
var resizeImage = function (file) {
|
||||
var tempPhotoFileName = "";
|
||||
if (encodingType == Camera.EncodingType.PNG) {
|
||||
tempPhotoFileName = "camera_cordova_temp_return.png";
|
||||
} else {
|
||||
tempPhotoFileName = "camera_cordova_temp_return.jpg";
|
||||
}
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
|
||||
Windows.Storage.FileIO.readBufferAsync(storageFile).then(function(buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
var imageData = "data:" + file.contentType + ";base64," + strBase64;
|
||||
var image = new Image();
|
||||
image.src = imageData;
|
||||
image.onload = function() {
|
||||
var imageWidth = targetWidth,
|
||||
imageHeight = targetHeight;
|
||||
var canvas = document.createElement('canvas');
|
||||
|
||||
canvas.width = imageWidth;
|
||||
canvas.height = imageHeight;
|
||||
|
||||
canvas.getContext("2d").drawImage(this, 0, 0, imageWidth, imageHeight);
|
||||
|
||||
var fileContent = canvas.toDataURL(file.contentType).split(',')[1];
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
|
||||
storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (storagefile) {
|
||||
var content = Windows.Security.Cryptography.CryptographicBuffer.decodeFromBase64String(fileContent);
|
||||
Windows.Storage.FileIO.writeBufferAsync(storagefile, content).then(function () {
|
||||
successCallback("ms-appdata:///local/" + storagefile.name);
|
||||
}, function () {
|
||||
errorCallback("Resize picture error.");
|
||||
});
|
||||
});
|
||||
};
|
||||
});
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder");
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
// because of asynchronous method, so let the successCallback be called in it.
|
||||
var resizeImageBase64 = function (file) {
|
||||
|
||||
Windows.Storage.FileIO.readBufferAsync(file).done( function(buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
var imageData = "data:" + file.contentType + ";base64," + strBase64;
|
||||
|
||||
var image = new Image();
|
||||
image.src = imageData;
|
||||
|
||||
image.onload = function() {
|
||||
var imageWidth = targetWidth,
|
||||
imageHeight = targetHeight;
|
||||
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);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
if (sourceType != Camera.PictureSourceType.CAMERA) {
|
||||
var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
|
||||
fileOpenPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
|
||||
if (mediaType == Camera.MediaType.PICTURE) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
|
||||
}
|
||||
else if (mediaType == Camera.MediaType.VIDEO) {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll([".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"]);
|
||||
}
|
||||
else {
|
||||
fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
|
||||
}
|
||||
|
||||
fileOpenPicker.pickSingleFileAsync().then(function (file) {
|
||||
if (file) {
|
||||
if (destinationType == Camera.DestinationType.FILE_URI) {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImage(file);
|
||||
}
|
||||
else {
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
|
||||
successCallback(URL.createObjectURL(storageFile));
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder.");
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(file);
|
||||
} else {
|
||||
Windows.Storage.FileIO.readBufferAsync(file).done(function (buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
successCallback(strBase64);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
errorCallback("User didn't choose a file.");
|
||||
}
|
||||
}, function () {
|
||||
errorCallback("User didn't choose a file.");
|
||||
});
|
||||
}
|
||||
else {
|
||||
|
||||
var cameraCaptureUI = new Windows.Media.Capture.CameraCaptureUI();
|
||||
cameraCaptureUI.photoSettings.allowCropping = true;
|
||||
var allowCrop = !!args[7];
|
||||
if (!allowCrop) {
|
||||
cameraCaptureUI.photoSettings.allowCropping = false;
|
||||
}
|
||||
|
||||
if (encodingType == Camera.EncodingType.PNG) {
|
||||
cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.png;
|
||||
} else {
|
||||
cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.jpeg;
|
||||
}
|
||||
|
||||
// decide which max pixels should be supported by targetWidth or targetHeight.
|
||||
if (targetWidth >= 1280 || targetHeight >= 960) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.large3M;
|
||||
}
|
||||
else if (targetWidth >= 1024 || targetHeight >= 768) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
|
||||
}
|
||||
else if (targetWidth >= 800 || targetHeight >= 600) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
|
||||
}
|
||||
else if (targetWidth >= 640 || targetHeight >= 480) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.smallVga;
|
||||
}
|
||||
else if (targetWidth >= 320 || targetHeight >= 240) {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.verySmallQvga;
|
||||
}
|
||||
else {
|
||||
cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.highestAvailable;
|
||||
}
|
||||
|
||||
cameraCaptureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (picture) {
|
||||
if (picture) {
|
||||
// save to photo album successCallback
|
||||
var success = function () {
|
||||
if (destinationType == Camera.DestinationType.FILE_URI) {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImage(picture);
|
||||
} else {
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
picture.copyAsync(storageFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
|
||||
successCallback("ms-appdata:///local/" + storageFile.name);
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder.");
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(picture);
|
||||
} else {
|
||||
Windows.Storage.FileIO.readBufferAsync(picture).done(function (buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
successCallback(strBase64);
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
// save to photo album errorCallback
|
||||
var fail = function () {
|
||||
//errorCallback("FileError, code:" + fileError.code);
|
||||
errorCallback("Save fail.");
|
||||
};
|
||||
|
||||
if (saveToPhotoAlbum) {
|
||||
Windows.Storage.StorageFile.getFileFromPathAsync(picture.path).then(function (storageFile) {
|
||||
storageFile.copyAsync(Windows.Storage.KnownFolders.picturesLibrary, picture.name, Windows.Storage.NameCollisionOption.generateUniqueName).then(function (storageFile) {
|
||||
success();
|
||||
}, function () {
|
||||
fail();
|
||||
});
|
||||
});
|
||||
//var directory = new DirectoryEntry("Pictures", parentPath);
|
||||
//new FileEntry(picture.name, picture.path).copyTo(directory, null, success, fail);
|
||||
} else {
|
||||
if (destinationType == Camera.DestinationType.FILE_URI) {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImage(picture);
|
||||
} else {
|
||||
|
||||
var storageFolder = Windows.Storage.ApplicationData.current.localFolder;
|
||||
picture.copyAsync(storageFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
|
||||
successCallback("ms-appdata:///local/" + storageFile.name);
|
||||
}, function () {
|
||||
errorCallback("Can't access localStorage folder.");
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (targetHeight > 0 && targetWidth > 0) {
|
||||
resizeImageBase64(picture);
|
||||
} else {
|
||||
Windows.Storage.FileIO.readBufferAsync(picture).done(function (buffer) {
|
||||
var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
|
||||
successCallback(strBase64);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
errorCallback("User didn't capture a photo.");
|
||||
}
|
||||
}, function () {
|
||||
errorCallback("Fail to capture a photo.");
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
require("cordova/exec/proxy").add("Camera",module.exports);
|
||||
33
tests/plugin.xml
Normal file
33
tests/plugin.xml
Normal file
@@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
|
||||
<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="org.apache.cordova.camera.tests"
|
||||
version="0.3.2">
|
||||
<name>Cordova Camera Plugin Tests</name>
|
||||
<license>Apache 2.0</license>
|
||||
|
||||
<dependency id="org.apache.cordova.file" version=">=1.0.1" />
|
||||
|
||||
<js-module src="tests.js" name="tests">
|
||||
</js-module>
|
||||
</plugin>
|
||||
504
tests/tests.js
Normal file
504
tests/tests.js
Normal file
@@ -0,0 +1,504 @@
|
||||
/*
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
*/
|
||||
|
||||
exports.defineAutoTests = function () {
|
||||
describe('Camera (navigator.camera)', function () {
|
||||
it("should exist", function () {
|
||||
expect(navigator.camera).toBeDefined();
|
||||
});
|
||||
|
||||
it("should contain a getPicture function", function () {
|
||||
expect(navigator.camera.getPicture).toBeDefined();
|
||||
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 () {
|
||||
expect(window.Camera).toBeDefined();
|
||||
});
|
||||
|
||||
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 () {
|
||||
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 () {
|
||||
expect(Camera.MediaType.PICTURE).toBe(0);
|
||||
expect(Camera.MediaType.VIDEO).toBe(1);
|
||||
expect(Camera.MediaType.ALLMEDIA).toBe(2);
|
||||
expect(navigator.camera.MediaType.PICTURE).toBe(0);
|
||||
expect(navigator.camera.MediaType.VIDEO).toBe(1);
|
||||
expect(navigator.camera.MediaType.ALLMEDIA).toBe(2);
|
||||
});
|
||||
|
||||
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);
|
||||
expect(navigator.camera.PictureSourceType.PHOTOLIBRARY).toBe(0);
|
||||
expect(navigator.camera.PictureSourceType.CAMERA).toBe(1);
|
||||
expect(navigator.camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
/******************************************************************************/
|
||||
|
||||
exports.defineManualTests = function (contentEl, createActionButton) {
|
||||
var platformId = cordova.require('cordova/platform').id;
|
||||
var pictureUrl = null;
|
||||
var fileObj = null;
|
||||
var fileEntry = null;
|
||||
var 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];
|
||||
|
||||
var clearLog = function () {
|
||||
var log = document.getElementById('info');
|
||||
log.innerHTML = "";
|
||||
}
|
||||
|
||||
function log(value) {
|
||||
console.log(value);
|
||||
document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n';
|
||||
}
|
||||
|
||||
function clearStatus() {
|
||||
document.getElementById('camera_status').innerHTML = '';
|
||||
document.getElementById('camera_image').src = 'about:blank';
|
||||
var canvas = document.getElementById('canvas');
|
||||
canvas.width = canvas.height = 1;
|
||||
pictureUrl = null;
|
||||
fileObj = null;
|
||||
fileEntry = null;
|
||||
}
|
||||
|
||||
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;
|
||||
} catch (e) {
|
||||
// not DATA_URL
|
||||
log('URL: ' + url.slice(0, 100));
|
||||
}
|
||||
|
||||
pictureUrl = url;
|
||||
var img = document.getElementById('camera_image');
|
||||
var startTime = new Date();
|
||||
img.src = url;
|
||||
img.onloadend = function () {
|
||||
log('Image tag load time: ' + (new Date() - startTime));
|
||||
callback && callback();
|
||||
};
|
||||
}
|
||||
|
||||
function onGetPictureError(e) {
|
||||
log('Error getting picture: ' + e.code);
|
||||
}
|
||||
|
||||
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) {
|
||||
resolveLocalFileSystemURI(data, function (e) {
|
||||
fileEntry = e;
|
||||
logCallback('resolveLocalFileSystemURI()', true)(e.toURL());
|
||||
}, logCallback('resolveLocalFileSystemURI()', false));
|
||||
} else if (pictureUrl.indexOf('data:image/jpeg;base64') == 0) {
|
||||
// do nothing
|
||||
} else {
|
||||
var path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' ');
|
||||
fileEntry = new FileEntry('image_name.png', path);
|
||||
}
|
||||
}
|
||||
|
||||
function getPicture() {
|
||||
clearStatus();
|
||||
var 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);
|
||||
}
|
||||
}
|
||||
|
||||
function uploadImage() {
|
||||
var ft = new FileTransfer(),
|
||||
uploadcomplete = 0,
|
||||
progress = 0,
|
||||
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://cordova-filetransfer.jitsu.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) {
|
||||
return function () {
|
||||
log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments)));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Select image from library using a NATIVE_URI destination type
|
||||
* 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";
|
||||
img.src = evt.target.result;
|
||||
log("FileReader.readAsDataURL success");
|
||||
};
|
||||
|
||||
function onFileReceived(file) {
|
||||
log('Got file: ' + JSON.stringify(file));
|
||||
fileObj = file;
|
||||
|
||||
var reader = new FileReader();
|
||||
reader.onload = function () {
|
||||
log('FileReader.readAsDataURL() - length = ' + reader.result.length);
|
||||
};
|
||||
reader.onerror = logCallback('FileReader.readAsDataURL', false);
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
// Test out onFileReceived when the file object was set via a native <input> elements.
|
||||
if (fileObj) {
|
||||
onFileReceived(fileObj);
|
||||
} else {
|
||||
fileEntry.file(onFileReceived, logCallback('FileEntry.file', false));
|
||||
}
|
||||
}
|
||||
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.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
|
||||
* This calls FileEntry.copyTo and FileEntry.moveTo.
|
||||
*/
|
||||
function copyImage() {
|
||||
var onFileSystemReceived = function (fileSystem) {
|
||||
var destDirEntry = fileSystem.root;
|
||||
var 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
|
||||
resolveLocalFileSystemURI(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
|
||||
resolveLocalFileSystemURI(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 () {
|
||||
console.log('Cleanup: failed to remove copied file');
|
||||
});
|
||||
};
|
||||
|
||||
window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, onFileSystemReceived, null);
|
||||
};
|
||||
|
||||
/**
|
||||
* Write image to library using a NATIVE_URI destination type
|
||||
* This calls FileEntry.createWriter, FileWriter.write, and FileWriter.truncate.
|
||||
*/
|
||||
function writeImage() {
|
||||
var onFileWriterReceived = function (fileWriter) {
|
||||
fileWriter.onwrite = logCallback('FileWriter.write', true);
|
||||
fileWriter.onerror = logCallback('FileWriter.write', false);
|
||||
fileWriter.write("some text!");
|
||||
};
|
||||
|
||||
var onFileTruncateWriterReceived = function (fileWriter) {
|
||||
fileWriter.onwrite = logCallback('FileWriter.truncate', true);
|
||||
fileWriter.onerror = logCallback('FileWriter.truncate', false);
|
||||
fileWriter.truncate(10);
|
||||
};
|
||||
|
||||
fileEntry.createWriter(onFileWriterReceived, logCallback('FileEntry.createWriter', false));
|
||||
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;
|
||||
h = 100 / w * h;
|
||||
w = 100;
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
var context = canvas.getContext('2d');
|
||||
context.drawImage(img, 0, 0, w, h);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove image from library using a NATIVE_URI destination type
|
||||
* This calls FileEntry.remove.
|
||||
*/
|
||||
function removeImage() {
|
||||
fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false));
|
||||
};
|
||||
|
||||
function testInputTag(inputEl) {
|
||||
clearStatus();
|
||||
// iOS 6 likes to dead-lock in the onchange context if you
|
||||
// do any alerts or try to remote-debug.
|
||||
window.setTimeout(function () {
|
||||
testNativeFile2(inputEl);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
function testNativeFile2(inputEl) {
|
||||
if (!inputEl.value) {
|
||||
alert('No file selected.');
|
||||
return;
|
||||
}
|
||||
fileObj = inputEl.files[0];
|
||||
if (!fileObj) {
|
||||
alert('Got value but no file.');
|
||||
return;
|
||||
}
|
||||
var URLApi = window.URL || window.webkitURL;
|
||||
if (URLApi) {
|
||||
var blobURL = URLApi.createObjectURL(fileObj);
|
||||
if (blobURL) {
|
||||
setPicture(blobURL, function () {
|
||||
URLApi.revokeObjectURL(blobURL);
|
||||
});
|
||||
} else {
|
||||
log('URL.createObjectURL returned null');
|
||||
}
|
||||
} else {
|
||||
log('URL.createObjectURL() not supported.');
|
||||
}
|
||||
}
|
||||
|
||||
function extractOptions() {
|
||||
var els = document.querySelectorAll('#image-options select');
|
||||
var ret = {};
|
||||
for (var i = 0, el; el = els[i]; ++i) {
|
||||
var value = el.value;
|
||||
if (value === '') continue;
|
||||
if (el.isBool) {
|
||||
ret[el.getAttribute("name")] = !!+value;
|
||||
} else {
|
||||
ret[el.getAttribute("name")] = +value;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
function createOptionsEl(name, values, selectionDefault) {
|
||||
var openDiv = '<div style="display: inline-block">' + name + ': ';
|
||||
var select = '<select name=' + name + '>';
|
||||
|
||||
var defaultOption = '';
|
||||
if (selectionDefault == undefined) {
|
||||
defaultOption = '<option value="">default</option>';
|
||||
}
|
||||
|
||||
var options = '';
|
||||
if (typeof values == 'boolean') {
|
||||
values = { 'true': 1, 'false': 0 };
|
||||
}
|
||||
for (var k in values) {
|
||||
var isSelected = '';
|
||||
if (selectionDefault) {
|
||||
if (selectionDefault[0] == k) {
|
||||
isSelected = 'selected';
|
||||
}
|
||||
}
|
||||
options += '<option value="' + values[k] + '" ' + isSelected + '>' + k + '</option>';
|
||||
}
|
||||
|
||||
var closeDiv = '</select></div>';
|
||||
|
||||
return openDiv + select + defaultOption + options + closeDiv;
|
||||
}
|
||||
|
||||
/******************************************************************************/
|
||||
|
||||
var 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 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('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>' +
|
||||
'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">' +
|
||||
'<ol> <li>All default options. Should be able to edit once picture is taken and will be saved to library.</li>' +
|
||||
'</p><li>sourceType=PHOTOLIBRARY<br>Should be able to see picture that was just taken in previous test and edit when selected</li>' +
|
||||
'</p><li>sourceType=Camera<br>allowEdit=false<br>saveToPhotoAlbum=false<br>Should not be able to edit when taken and will not save to library</li>' +
|
||||
'</p><li>encodingType=PNG<br>allowEdit=true<br>saveToPhotoAlbum=true<br>cameraDirection=FRONT<br>Should bring up front camera. Verify in status box info URL that image is encoded as PNG.</li>' +
|
||||
'</p><li>sourceType=SAVEDPHOTOALBUM<br>mediaType=VIDEO<br>Should only be able to select a video</li>' +
|
||||
'</p><li>sourceType=SAVEDPHOTOALBUM<br>mediaType=PICTURE<br>allowEdit=false<br>Should only be able to select a picture and not edit</li>' +
|
||||
'</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>' +
|
||||
'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>' +
|
||||
'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"' +
|
||||
'</p><div id="reader"></div>' +
|
||||
'Expected result: Read contents of file.<br>Status box will show "Got file: {some metadata}, FileReader.readAsDataURL() - length = someNumber"' +
|
||||
'</p><div id="copy"></div>' +
|
||||
'Expected result: Copy image to new location and move file to different location.<br>Status box will show "Call to FileEntry.copyTo success:{some metadata}, Call to FileEntry.moveTo success:{some metadata}"' +
|
||||
'</p><div id="write"></div>' +
|
||||
'Expected result: Write image to library.<br>Status box will show "Call to FileWriter.write success:{some metadata}, Call to FileWriter.truncate success:{some metadata}"' +
|
||||
'</p><div id="upload"></div>' +
|
||||
'Expected result: Upload image to server.<br>Status box may print out progress. Once finished will show "upload complete"' +
|
||||
'</p><div id="draw_canvas"></div>' +
|
||||
'Expected result: Display image using canvas.<br>Image will be displayed in status box under "canvas:"' +
|
||||
'</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;
|
||||
}
|
||||
|
||||
var elements = document.getElementsByClassName("testInputTag");
|
||||
var listener = function (e) {
|
||||
testInputTag(e.target);
|
||||
}
|
||||
for (var i = 0; i < elements.length; ++i) {
|
||||
var item = elements[i];
|
||||
item.addEventListener("change", listener, false);
|
||||
}
|
||||
|
||||
createActionButton('Get picture', function () {
|
||||
getPicture();
|
||||
}, 'getpicture');
|
||||
|
||||
createActionButton('Clear Status', function () {
|
||||
clearStatus();
|
||||
}, 'getpicture');
|
||||
|
||||
createActionButton('Get File Metadata', function () {
|
||||
getFileInfo();
|
||||
}, 'metadata');
|
||||
|
||||
createActionButton('Read with FileReader', function () {
|
||||
readFile();
|
||||
}, 'reader');
|
||||
|
||||
createActionButton('Copy Image', function () {
|
||||
copyImage();
|
||||
}, 'copy');
|
||||
|
||||
createActionButton('Write Image', function () {
|
||||
writeImage();
|
||||
}, 'write');
|
||||
|
||||
createActionButton('Upload Image', function () {
|
||||
uploadImage();
|
||||
}, 'upload');
|
||||
|
||||
createActionButton('Draw Using Canvas', function () {
|
||||
displayImageUsingCanvas();
|
||||
}, 'draw_canvas');
|
||||
|
||||
createActionButton('Remove Image', function () {
|
||||
removeImage();
|
||||
}, 'remove');
|
||||
};
|
||||
82
www/blackberry10/assets/camera.html
Normal file
82
www/blackberry10/assets/camera.html
Normal file
@@ -0,0 +1,82 @@
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<!DOCTYPE HTML>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<script src="camera.js" type="text/javascript"></script>
|
||||
<script>
|
||||
var meta = document.createElement("meta");
|
||||
meta.setAttribute('name','viewport');
|
||||
meta.setAttribute('content','initial-scale='+ (1/window.devicePixelRatio) + ',user-scalable=no');
|
||||
document.getElementsByTagName('head')[0].appendChild(meta);
|
||||
</script>
|
||||
</head>
|
||||
<style type="text/css">
|
||||
body {
|
||||
background-color: black;
|
||||
}
|
||||
.action-bar {
|
||||
position: fixed;
|
||||
left: 0px;
|
||||
bottom: 0px;
|
||||
height: 100px;
|
||||
width: 100%;
|
||||
background-image: linear-gradient(rgb(41, 41, 41), rgb(32, 32, 32));
|
||||
}
|
||||
.action-bar-back {
|
||||
width: 78px;
|
||||
height: 100px;
|
||||
background-color: black;
|
||||
}
|
||||
.action-bar-divider {
|
||||
position: fixed;
|
||||
bottom: 0px;
|
||||
left: 78px;
|
||||
width: 28px;
|
||||
height: 100px;
|
||||
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAABkCAYAAACVfFA4AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3ggLDiUo1ElOKAAABHdJREFUaN612ktvE1cUB/Bz7bGdGcePJk1i4tA0DomCRJUQEGphAa3KQwGpUHWFYMEiIBZdtKgfADbdsekXaFW1XZUuQAiFh0BRi+iqap2EJrUSJSjg2I7Hk3GmdmwPi5Z4ziQEx57/XeXKUn6255w558y1ICKTUOvKverfpkl0/ahwEXKZ1c/iLhlERAQDu85etcrkX3mGBbPhPiIhXnkUyPyNBfO+1upGEIUyU1iQXG52LSd/HRNY0BIwPiNbfR8Iq+3CN5brZ5KiJrBgLrCT7cPpKSxYlPyWgBE0e/d7AQMHDh0nEhavVOSx5DRodA6zm6WSX8SC2dYBFjCvEh4GrsjtbB9MT2BB0+Vh++nx2wIG7jp2liW8VNQ23oAc/To79lavH5nkV+ewoBrqsVak9Rs2DCx4Q6xCfDbUKcHA/R+dsnydRKJSputfXyvDwHSgl1cIPbl51XLs+rXvYQnfnJ3BgprSyfah1AQWrLh9ZI2YxKNfBAzs//A0a2/da/nXdx5OgHpkH9sr2jwWVFv6eIVIT2HBVV8Lq/DB9CQWZP/GrNDTJw8FDIydHGUB4zXStb61OvOvY5BXiOUEFlSb3+EVYouAcQQsSTKrEHP3fxQwsP/gCdYSukqF7YRXHS1hlLeE8v8zIAzMtu62tYTTWDAvt7HrF0jFsaApJBahM7+NCRjYe+wcS3hPIbfde9I2W8LIEK8Q2QQWVEMxFjDB1CQWLHoCrEIs3P1OwMD/WkKLV16rp67UvpYCu1jCN+kvsKC9JfQvT2NBXdnB9rUkfEMgawkF0ez4TQEDe4+c4S1hMV9vM1Jjw7RjH3vapGwyAzoKqm/1sSmp+Q0VvmHQ8IVZwn85MuSFguwpYaVMX31+eQ0Gdo9cZDOgdzXdSAdbQ0sYGeQBk5nBgiuBnSxggqm/sGDJrbCAmX/0s4CBvQdPsIR3rRmNTiFvagmtM6BJsraABXMtA+xYwJ96igVXlTZbhZjAgqZLYl9p4vf7Agb2fHyOPyU0VCdG1y3yr3Mvr/A1toR1g1qwh+39S3EsWPTylnDxwQ8CBg7bW0LbsYDj4FKQt4Q+/TkW1Nre4+dIqSksqPt5SxhMxbFgxW09FhA09/iOgIGxw2fY9XMXdSefWW0yUkeHWYTK6iwW1MJ9tC6aJvlrnAHrBo0m/pTwxtVRFxQk6+8KKmU69P4BEwZ2j4w23BJuC1Q7hnjC284BHQd128FxczKOBcuSwhL+2fgNAQNjHxznLWHJIKfWpqDRxY8FmnILWFCzPSV0IuG3BPPK2yzho//OYUESHjYl/fHgloCB3UfPs4T3GMvk5NoA5iODvEJk/sGCWijGK8RSHAvaW8LnD38SUJDFTrlITi8GRj/5gr3oW1nEglo7bwnlOmfAmkFdiVjv1xRI/okFTclrHQFp/smYgIHvHv6U/5awoBFirYOr0WH2gpydxYK5cD+vEA4n/Aaw0BRiCZ+8962AgrwlLBFquYiIuk5ess2ASRgoERHp7XtIUGUdlTPTVACBLwEignyX5voIbgAAAABJRU5ErkJggg==);
|
||||
}
|
||||
.action-bar-back-button {
|
||||
position: fixed;
|
||||
bottom: 35px;
|
||||
left: 34px;
|
||||
width: 18px;
|
||||
height: 28px;
|
||||
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAcCAYAAABsxO8nAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3ggLDh43ZfOs5QAAAvdJREFUOMuVlU9LMm0Uh6+ZRguUKaNoWbs0QVIMCb9CqQtb1UdI2lS0dBNhn6D2EVQQLaM2UZpTUknRwm3UooI2lTZ/9H42b/M+g2k+A/fmPjcXF+f8OAMg/vVEIhFRLBbF4+Oj0DRNjI2NCem/YsdfJBJhf38fWZbtu4eHBzoGSZJELBZjZ2cHSZKa6nKnkKmpKQ4ODgAQQjhOpVL53UiWZaanp9nY2EDX9ab6+/s76XS6vVFXVxepVIrNzc0fIU9PTySTSSqVCkoriKIozM7OksvlqNVqjpoQwoa8vb217pHL5SKTybC+vk61WnX0o9FocH9/TyKRsCFAs5Hb7SaTybC8vMzn56ej1mg0uL29ZWZmhnq93npqHo+HhYUFlpaW+Pj4sC0ALMuiUCiQTqebIA4jr9dLNptlbm7OYSJJEqZpcnx8zPz8fOuIAEJVVdbW1kilUo7GSpJErVbj8PCQxcXF9lnz+XxidXWVRCLRNJ1qtcr29ja5XO7X0MorKyskk8kmiCzLHB0ddQQBkF9eXnh9fUWSpKboK4rCwMBAR6CuYrGYdbvdBAIBuru77SkJIQiFQoyMjKBpGtVqtT0IyF5cXKAoCuFwGEX5P1qWZeH3+xkeHiafz/P19dUeBFAqlejr68Pv9+NyuWwz0zQJBAKoqkq5XG7qZRMI4OzsDFVVCQQCuFwu+5FhGExMTKCqKtfX1z/CHCCAQqGA1+tlfHzcHgCArutEo1E8Hg+lUgnDMNqDAM7PzxkcHMTv9yPLsg0zDINoNIosy9zd3TlWy48ggJOTE/r7+wkGg47Vapom8XgcRVG4ubmxzVqCAE5PT+nt7SUcDtNoNOx7XdeZnJwE4OrqCsuy2oMA8vk8Q0NDBINBxzYwDINYLMb3xH8FfZv5fD5CoZAN+s5ZPB5H07TOQEII8vk8qqoSjUaxLMu2M02T5+fnzn5HAPV6nVwux+7uLm63277v6emhXC53ZvT3qr28vMTn8zE6OgrA3t4eW1tb/AH4Zo+8fEoEngAAAABJRU5ErkJggg==);
|
||||
}
|
||||
.camera-cross-hairs {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
-webkit-transform: translate(-50%, -147px);
|
||||
width: 194px;
|
||||
height: 195px;
|
||||
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAQAAAB6tAYfAAAAAmJLR0QA/4ePzL8AAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfeCAsPDxicOdibAAACbElEQVR42u3a7U7aYBgG4Oet0yZLTMx2bDu5nYo7nSUmzi34DUSe/bA0UHSDbpS5Xpc/sECNuW/a5yV5I4CI8toL03y31R94ipMy7gj/PKmNp7/lWSx27PEuzkZaxFWe7viJL3EdH8ovS5hnRkTu+K9UcVzGehX0u/WsXxNVt4LcuYLoccb/ok9WGRHzfKWEWS56xvkw2hLue1a3WKuh9L+wluqRD+bH7BdA6Q7qr59mOW1/LBr3Wdky5VlenK9dCattjv2TPdwwXy5oqu4iSQX7VpfsjPVq7OubQ1i8VMLFefndF2j24i7b1O/z6LWJzT4Wtp28K5EcnhKUgBKUgBKUgBKUgBKUgBKUgBKUgBKUgBLeSglP7eFMIgPo5t3Zd2TDyzCWe4/q1X1HPz5HREykM5BJyBsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWhfn05zl95TEMC5zmrO8bPIuzw+zfD44LgIawjxzJe8qIuI2MzIyFnHnWhjATS6avG+zLaFqXz6W0ACO2t9OYj1/DkYJSkAJSkAJSkAJSkAJSkAJSkAJSkAJSkAJb6WE6y+COIzbiGh3WzxmaQ5P7LfYu4dc3oDq4nb0j8yA5ni50yWbHUjsz2bCTQmTlakwVcMeraZ73TyWzftUiYiMjO2Gw1O8H/kUuc+jrd6XUZpsY20ixGrSy+HceXoLN/FxpEVc5elO71+9ydTlxbT73oiq0e5hneei55l1eWVQ1z2jHO8Qyb9QwcZqqS6TPuve8a74e5wz2fiwl22m+C6tjnu9IyngTfsJ8D+4z5r15Y4AAAAASUVORK5CYII=);
|
||||
}
|
||||
</style>
|
||||
<body>
|
||||
<div id="camera">
|
||||
<video id="v"></video>
|
||||
<div class="camera-cross-hairs"></div>
|
||||
</div>
|
||||
<canvas id="c" style="display: none;"></canvas>
|
||||
<div class="action-bar">
|
||||
<div id="back" class="action-bar-back">
|
||||
<div class="action-bar-back-button"></div>
|
||||
</div>
|
||||
<div class="action-bar-divider"></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
46
www/blackberry10/assets/camera.js
Normal file
46
www/blackberry10/assets/camera.js
Normal 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.
|
||||
*
|
||||
*/
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
document.getElementById('back').onclick = function () {
|
||||
window.qnx.callExtensionMethod('org.apache.cordova.camera', 'cancel');
|
||||
};
|
||||
window.navigator.webkitGetUserMedia(
|
||||
{ video: true },
|
||||
function (stream) {
|
||||
var video = document.getElementById('v'),
|
||||
canvas = document.getElementById('c'),
|
||||
camera = document.getElementById('camera');
|
||||
video.autoplay = true;
|
||||
video.width = window.innerWidth;
|
||||
video.height = window.innerHeight - 100;
|
||||
video.src = window.webkitURL.createObjectURL(stream);
|
||||
camera.onclick = function () {
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
|
||||
window.qnx.callExtensionMethod('org.apache.cordova.camera', canvas.toDataURL('img/png'));
|
||||
};
|
||||
},
|
||||
function () {
|
||||
window.qnx.callExtensionMethod('org.apache.cordova.camera', 'error', 'getUserMedia failed');
|
||||
}
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user