Why Does My Photo Rotate When I Upload It Sencha Cordova Camera Lugin

cordova-plugin-camera

Android Testsuite Chrome Testsuite iOS Testsuite Lint Test

This plugin defines a global navigator.camera object, which provides an API for taking pictures and for choosing images from the system'southward image library.

Although the object is fastened to the global scoped navigator, it is not available until after the deviceready event.

            document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() {     console.log(navigator.camera); }                      

Installation

This requires cordova 5.0+

            cordova plugin add cordova-plugin-camera Older versions of cordova can even so install via the __deprecated__ id  cordova plugin add org.apache.cordova.photographic camera It is also possible to install via repo url direct ( unstable )  cordova plugin add https://github.com/apache/cordova-plugin-photographic camera.git                      

How to Contribute

Contributors are welcome! And nosotros need your contributions to continue the project moving forward. You tin[report bugs, better the documentation, or contribute code.

There is a specific contributor workflow nosotros recommend. Start reading there. More data is available on our wiki.

Have a solution? Send a Pull Request.

In order for your changes to exist accepted, you lot need to sign and submit an Apache ICLA (Individual Contributor License Agreement). Then your name will appear on the list of CLAs signed past non-committers or Cordova committers.

And don't forget to test and document your code.

iOS Quirks

Since iOS 10 it's mandatory to provide an usage description in the info.plist if trying to admission privacy-sensitive data. When the arrangement prompts the user to allow access, this usage clarification cord volition displayed every bit office of the permission dialog box, but if you didn't provide the usage description, the app will crash before showing the dialog. Too, Apple will reject apps that access private data merely don't provide an usage description.

This plugins requires the following usage descriptions:

  • NSCameraUsageDescription specifies the reason for your app to admission the device's camera.
  • NSPhotoLibraryUsageDescription specifies the reason for your app to access the user'due south photo library.
  • NSLocationWhenInUseUsageDescription specifies the reason for your app to admission the user'south location data while your app is in apply. (Set it if you accept CameraUsesGeolocation preference set to true)
  • NSPhotoLibraryAddUsageDescription specifies the reason for your app to get write-only access to the user'south photo library

To add these entries into the info.plist, you can use the edit-config tag in the config.xml like this:

            <edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">     <cord>demand camera access to take pictures</string> </edit-config>                      
            <edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge">     <string>need photograph library access to get pictures from there</string> </edit-config>                      
            <edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" fashion="merge">     <string>need location access to notice things nearby</cord> </edit-config>                      
            <edit-config target="NSPhotoLibraryAddUsageDescription" file="*-Info.plist" fashion="merge">     <string>need photo library access to relieve pictures there</cord> </edit-config>                      

API Reference

  • camera
    • .getPicture(successCallback, errorCallback, options)
    • .cleanup()
    • .onError : role
    • .onSuccess : role
    • .CameraOptions : Object
  • Photographic camera
    • .DestinationType : enum
    • .EncodingType : enum
    • .MediaType : enum
    • .PictureSourceType : enum
    • .PopoverArrowDirection : enum
    • .Management : enum
  • CameraPopoverHandle
  • CameraPopoverOptions

camera

photographic camera.getPicture(successCallback, errorCallback, options)

Takes a photo using the camera, or retrieves a photo from the device'due south image gallery. The epitome is passed to the success callback as a Base64-encoded Cord, or as the URI for the image file.

The camera.getPicture function opens the device's default camera awarding that allows users to snap pictures by default - this beliefs occurs, when Photographic camera.sourceType equals Camera.PictureSourceType.CAMERA. Once the user snaps the photo, the camera application closes and the application is restored.

If Camera.sourceType is Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, so a dialog displays that allows users to select an existing image.

The render value is sent to the cameraSuccess callback function, in one of the post-obit formats, depending on the specified cameraOptions:

  • A String containing the Base64-encoded photo image.
  • A String representing the image file location on local storage (default).

You tin can practise whatever you lot want with the encoded prototype or URI, for case:

  • Render the image in an <img> tag, as in the example beneath
  • Save the information locally (LocalStorage, Lawnchair, etc.)
  • Post the data to a remote server

NOTE: Photo resolution on newer devices is quite good. Photos selected from the device's gallery are not downscaled to a lower quality, even if a quality parameter is specified. To avert mutual memory problems, ready Photographic camera.destinationType to FILE_URI rather than DATA_URL.

Supported Platforms

  • Android
  • Browser
  • iOS
  • Windows
  • OSX

More examples here. Quirks here.

Kind: static method of [camera](#module_camera)

Param Blazon Description
successCallback [onSuccess](#module_camera.onSuccess)
errorCallback [onError](#module_camera.onError)
options [CameraOptions](#module_camera.CameraOptions) CameraOptions

Example

                          navigator              .              camera              .              getPicture              (              cameraSuccess              ,              cameraError              ,              cameraOptions              );                      

camera.cleanup()

Removes intermediate paradigm files that are kept in temporary storage subsequently calling camera.getPicture. Applies simply when the value of Camera.sourceType equals Camera.PictureSourceType.Photographic camera and the Camera.destinationType equals Camera.DestinationType.FILE_URI.

Supported Platforms

  • iOS

Kind: static method of [camera](#module_camera)
Example

                          navigator              .              camera              .              cleanup              (              onSuccess              ,              onFail              );              office              onSuccess              ()              {              panel              .              log              (              "              Camera cleanup success.              "              )              }              role              onFail              (              bulletin              )              {              alert              (              '              Failed because:                            '              +              message              );              }                      

camera.onError : function

Callback function that provides an error message.

Kind: static typedef of [camera](#module_camera)

Param Type Clarification
bulletin string The bulletin is provided by the device'due south native code.

camera.onSuccess : function

Callback part that provides the image data.

Kind: static typedef of [camera](#module_camera)

Param Blazon Description
imageData string Base64 encoding of the image data, or the image file URI, depending on cameraOptions in effect.

Example

                          // Show epitome              //              function              cameraCallback              (              imageData              )              {              var              image              =              document              .              getElementById              (              '              myImage              '              );              image              .              src              =              "              data:paradigm/jpeg;base64,              "              +              imageData              ;              }                      

photographic camera.CameraOptions : Object

Optional parameters to customize the photographic camera settings.

  • Quirks

Kind: static typedef of [camera](#module_camera)
Properties

Name Type Default Description
quality number 50 Quality of the saved paradigm, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. (Note that information nearly the camera's resolution is unavailable.)
destinationType [DestinationType](#module_Camera.DestinationType) FILE_URI Choose the format of the return value.
sourceType [PictureSourceType](#module_Camera.PictureSourceType) CAMERA Ready the source of the movie.
allowEdit Boolean simulated Let simple editing of image before pick.
encodingType [EncodingType](#module_Camera.EncodingType) JPEG Cull the returned image file'south encoding.
targetWidth number Width in pixels to scale paradigm. Must be used with targetHeight. Aspect ratio remains constant.
targetHeight number Pinnacle in pixels to scale image. Must be used with targetWidth. Attribute ratio remains constant.
mediaType [MediaType](#module_Camera.MediaType) PICTURE Set the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM.
correctOrientation Boolean Rotate the image to correct for the orientation of the device during capture.
saveToPhotoAlbum Boolean Salvage the image to the photo album on the device afterwards capture.
popoverOptions [CameraPopoverOptions](#module_CameraPopoverOptions) iOS-only options that specify popover location in iPad.
cameraDirection [Direction](#module_Camera.Direction) BACK Choose the photographic camera to utilise (front- or dorsum-facing).

Camera

Camera.DestinationType : enum

Defines the output format of Photographic camera.getPicture call.

Kind: static enum property of [Camera](#module_Camera)
Properties

Name Blazon Default Clarification
DATA_URL number 0 Return base64 encoded cord. DATA_URL can be very retentivity intensive and cause app crashes or out of memory errors. Use FILE_URI if possible
FILE_URI number 1 Return file uri (content://media/external/images/media/two for Android)

Camera.EncodingType : enum

Kind: static enum property of [Photographic camera](#module_Camera)
Backdrop

Proper noun Type Default Description
JPEG number 0 Render JPEG encoded epitome
PNG number 1 Return PNG encoded paradigm

Camera.MediaType : enum

Kind: static enum belongings of [Camera](#module_Camera)
Properties

Name Type Default Description
PICTURE number 0 Allow choice of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO number 1 Allow selection of video only, ONLY RETURNS URL
ALLMEDIA number 2 Allow selection from all media types

Photographic camera.PictureSourceType : enum

Defines the output format of Camera.getPicture phone call.

Kind: static enum property of [Camera](#module_Camera)
Properties

Proper noun Type Default Description
PHOTOLIBRARY number 0 Choose image from the device'due south photograph library (same as SAVEDPHOTOALBUM for Android)
CAMERA number 1 Take picture from camera
SAVEDPHOTOALBUM number 2 Choose image only from the device's Camera Coil album (same as PHOTOLIBRARY for Android)

Camera.PopoverArrowDirection : enum

Matches iOS UIPopoverArrowDirection constants to specify arrow location on popover.

Kind: static enum belongings of [Photographic camera](#module_Camera)
Properties

Proper noun Type Default
ARROW_UP number ane
ARROW_DOWN number 2
ARROW_LEFT number four
ARROW_RIGHT number 8
ARROW_ANY number 15

Camera.Management : enum

Kind: static enum property of [Camera](#module_Camera)
Backdrop

Name Type Default Description
Dorsum number 0 Use the back-facing camera
FRONT number 1 Apply the forepart-facing photographic camera

CameraPopoverOptions

iOS-only parameters that specify the anchor element location and pointer direction of the popover when selecting images from an iPad'southward library or album. Note that the size of the popover may change to adjust to the management of the arrow and orientation of the screen. Brand sure to account for orientation changes when specifying the anchor chemical element location.

Param Type Default Description
[x] Number 0 x pixel coordinate of screen chemical element onto which to anchor the popover.
[y] Number 32 y pixel coordinate of screen element onto which to anchor the popover.
[width] Number 320 width, in pixels, of the screen element onto which to ballast the popover.
[acme] Number 480 elevation, in pixels, of the screen element onto which to anchor the popover.
[arrowDir] [PopoverArrowDirection](#module_Camera.PopoverArrowDirection) ARROW_ANY Direction the arrow on the popover should point.
[popoverWidth] Number 0 width of the popover (0 or non specified will apply apple'south default width).
[popoverHeight] Number 0 summit of the popover (0 or not specified will employ apple tree'due south default pinnacle).

CameraPopoverHandle

A handle to an image picker popover.

Supported Platforms

  • iOS

Example

                          navigator              .              camera              .              getPicture              (              onSuccess              ,              onFail              ,              {              destinationType              :              Camera              .              DestinationType              .              FILE_URI              ,              sourceType              :              Photographic camera              .              PictureSourceType              .              PHOTOLIBRARY              ,              popoverOptions              :              new              CameraPopoverOptions              (              300              ,              300              ,              100              ,              100              ,              Camera              .              PopoverArrowDirection              .              ARROW_ANY              ,              300              ,              600              )              });              // Reposition the popover if the orientation changes.              window              .              onorientationchange              =              function              ()              {              var              cameraPopoverHandle              =              new              CameraPopoverHandle              ();              var              cameraPopoverOptions              =              new              CameraPopoverOptions              (              0              ,              0              ,              100              ,              100              ,              Photographic camera              .              PopoverArrowDirection              .              ARROW_ANY              ,              400              ,              500              );              cameraPopoverHandle              .              setPosition              (              cameraPopoverOptions              );              }                      

camera.getPicture Errata

Case

Take a photo and remember the image's file location:

            navigator.camera.getPicture(onSuccess, onFail, { quality: 50,     destinationType: Camera.DestinationType.FILE_URI });  function onSuccess(imageURI) {     var image = document.getElementById('myImage');     epitome.src = imageURI; }  office onFail(message) {     alert('Failed because: ' + message); }                      

Accept a photo and retrieve it as a Base64-encoded image:

            /**  * Warning: Using DATA_URL is not recommended! The DATA_URL destination  * blazon is very memory intensive, fifty-fifty with a depression quality setting. Using it  * tin effect in out of retentiveness errors and application crashes. Use FILE_URI  * instead.  */ navigator.camera.getPicture(onSuccess, onFail, { quality: 25,     destinationType: Photographic camera.DestinationType.DATA_URL });  function onSuccess(imageData) {     var image = document.getElementById('myImage');     image.src = "data:prototype/jpeg;base64," + imageData; }  function onFail(message) {     warning('Failed because: ' + message); }                      

Preferences (iOS)

  • CameraUsesGeolocation (boolean, defaults to false). For capturing JPEGs, set to true to get geolocation information in the EXIF header. This will trigger a request for geolocation permissions if set up to true.

                                      <preference proper noun="CameraUsesGeolocation" value="faux" />                              

Android Quirks

Android uses intents to launch the photographic camera activeness on the device to capture images, and on phones with low retentivity, the Cordova action may be killed. In this scenario, the effect from the plugin phone call will be delivered via the resume event. See the Android Lifecycle guide for more information. The pendingResult.event value will contain the value that would be passed to the callbacks (either the URI/URL or an error bulletin). Check the pendingResult.pluginStatus to determine whether or not the call was successful.

Browser Quirks

Can just render photos equally Base64-encoded image.

iOS Quirks

Including a JavaScript warning() in either of the callback functions can cause issues. Wrap the alarm within a setTimeout() to allow the iOS paradigm picker or popover to fully close earlier the warning displays:

            setTimeout(function() {     // do your thing here! }, 0);                      

Windows quirks

On Windows Phone eight.ane using SAVEDPHOTOALBUM or PHOTOLIBRARY every bit a source type causes application to suspend until file picker returns the selected image and so restore with outset page equally defined in app'southward config.xml. In example when camera.getPicture was called from different folio, this will lead to reloading start folio from scratch and success and error callbacks will never be called.

To avoid this we suggest using SPA pattern or call camera.getPicture only from your app'south first page.

More data about Windows Phone 8.i picker APIs is here: How to continue your Windows Phone app after calling a file picker

CameraOptions Errata

Android Quirks

  • Whatsoever cameraDirection value results in a dorsum-facing photo. (= You can only use the back camera)

  • allowEdit is unpredictable on Android and it should non be used! The Android implementation of this plugin tries to find and use an application on the user'due south device to do image cropping. The plugin has no command over what awarding the user selects to perform the image cropping and it is very possible that the user could choose an incompatible pick and cause the plugin to fail. This sometimes works because well-nigh devices come up with an application that handles cropping in a way that is compatible with this plugin (Google Photos), but it is unwise to rely on that beingness the case. If image editing is essential to your application, consider seeking a 3rd party library or plugin that provides its own image editing utility for a more robust solution.

  • Camera.PictureSourceType.PHOTOLIBRARY and Camera.PictureSourceType.SAVEDPHOTOALBUM both brandish the same photo anthology.

  • Ignores the encodingType parameter if the prototype is unedited (i.due east. quality is 100, correctOrientation is simulated, and no targetHeight or targetWidth are specified). The Camera source will always return the JPEG file given by the native camera and the PHOTOLIBRARY and SAVEDPHOTOALBUM sources will return the selected file in its existing encoding.

iOS Quirks

  • When using destinationType.FILE_URI, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends.

Sample: Have Pictures, Select Pictures from the Picture Library, and Get Thumbnails

The Camera plugin allows you lot to do things like open the device'south Camera app and take a film, or open the file picker and select 1. The lawmaking snippets in this section demonstrate dissimilar tasks including:

  • Open up the Photographic camera app and accept a Picture
  • Take a motion-picture show and return thumbnails (resized picture)
  • Take a picture and generate a FileEntry object
  • Select a file from the movie library
  • Select a JPEG prototype and return thumbnails (resized prototype)
  • Select an image and generate a FileEntry object

Take a Picture

Before y'all tin take a picture, you lot need to set some Camera plugin options to pass into the Camera plugin'south getPicture function. Here is a common set of recommendations. In this example, you create the object that you will use for the Camera options, and fix the sourceType dynamically to back up both the Camera app and the file picker.

                          function              setOptions              (              srcType              )              {              var              options              =              {              // Some common settings are 20, fifty, and 100              quality              :              50              ,              destinationType              :              Photographic camera              .              DestinationType              .              FILE_URI              ,              // In this app, dynamically set up the picture source, Camera or photograph gallery              sourceType              :              srcType              ,              encodingType              :              Photographic camera              .              EncodingType              .              JPEG              ,              mediaType              :              Camera              .              MediaType              .              PICTURE              ,              allowEdit              :              true              ,              correctOrientation              :              true              }              return              options              ;              }                      

Typically, yous want to use a FILE_URI instead of a DATA_URL to avoid almost memory issues. JPEG is the recommended encoding type for Android.

You lot take a film past passing in the options object to getPicture, which takes a CameraOptions object as the third statement. When y'all call setOptions, pass Camera.PictureSourceType.CAMERA as the pic source.

                          function              openCamera              (              selection              )              {              var              srcType              =              Camera              .              PictureSourceType              .              Camera              ;              var              options              =              setOptions              (              srcType              );              var              func              =              createNewFileEntry              ;              navigator              .              photographic camera              .              getPicture              (              function              cameraSuccess              (              imageUri              )              {              displayImage              (              imageUri              );              // You may choose to copy the motion-picture show, save information technology somewhere, or upload.              func              (              imageUri              );              },              function              cameraError              (              error              )              {              panel              .              debug              (              "              Unable to obtain picture:                            "              +              fault              ,              "              app              "              );              },              options              );              }                      

Once yous accept the movie, y'all can display information technology or do something else. In this example, call the app's displayImage function from the preceding code.

                          function              displayImage              (              imgUri              )              {              var              elem              =              certificate              .              getElementById              (              '              imageFile              '              );              elem              .              src              =              imgUri              ;              }                      

To display the epitome on some platforms, yous might need to include the main role of the URI in the Content-Security-Policy <meta> element in index.html. For example, on Windows 10, y'all can include ms-appdata: in your <meta> element. Here is an example.

                          <meta              http-equiv=              "Content-Security-Policy"              content=              "default-src 'self' data: gap: ms-appdata: https://ssl.gstatic.com 'dangerous-eval'; style-src 'cocky' 'unsafe-inline'; media-src *"              >                      

Take a Picture and Return Thumbnails (Resize the Motion picture)

To get smaller images, yous can render a resized image by passing both targetHeight and targetWidth values with your CameraOptions object. In this case, you resize the returned image to fit in a 100px by 100px box (the attribute ratio is maintained, then 100px is either the summit or width, whichever is greater in the source).

                          role              openCamera              (              option              )              {              var              srcType              =              Camera              .              PictureSourceType              .              Camera              ;              var              options              =              setOptions              (              srcType              );              var              func              =              createNewFileEntry              ;              if              (              selection              ==              "              photographic camera-thmb              "              )              {              options              .              targetHeight              =              100              ;              options              .              targetWidth              =              100              ;              }              navigator              .              camera              .              getPicture              (              function              cameraSuccess              (              imageUri              )              {              // Do something              },              office              cameraError              (              error              )              {              console              .              debug              (              "              Unable to obtain picture:                            "              +              error              ,              "              app              "              );              },              options              );              }                      

Select a File from the Picture Library

When selecting a file using the file picker, you likewise need to set the CameraOptions object. In this case, ready the sourceType to Camera.PictureSourceType.SAVEDPHOTOALBUM. To open the file picker, call getPicture just every bit you did in the previous instance, passing in the success and error callbacks along with CameraOptions object.

                          role              openFilePicker              (              selection              )              {              var              srcType              =              Camera              .              PictureSourceType              .              SAVEDPHOTOALBUM              ;              var              options              =              setOptions              (              srcType              );              var              func              =              createNewFileEntry              ;              navigator              .              photographic camera              .              getPicture              (              function              cameraSuccess              (              imageUri              )              {              // Practice something              },              function              cameraError              (              error              )              {              console              .              debug              (              "              Unable to obtain picture:                            "              +              fault              ,              "              app              "              );              },              options              );              }                      

Select an Image and Return Thumbnails (resized images)

Resizing a file selected with the file picker works just like resizing using the Camera app; set the targetHeight and targetWidth options.

                          part              openFilePicker              (              choice              )              {              var              srcType              =              Camera              .              PictureSourceType              .              SAVEDPHOTOALBUM              ;              var              options              =              setOptions              (              srcType              );              var              func              =              createNewFileEntry              ;              if              (              selection              ==              "              picker-thmb              "              )              {              // To downscale a selected image,              // Camera.EncodingType (due east.yard., JPEG) must lucifer the selected image blazon.              options              .              targetHeight              =              100              ;              options              .              targetWidth              =              100              ;              }              navigator              .              camera              .              getPicture              (              function              cameraSuccess              (              imageUri              )              {              // Practise something with image              },              office              cameraError              (              error              )              {              console              .              debug              (              "              Unable to obtain motion picture:                            "              +              error              ,              "              app              "              );              },              options              );              }                      

Take a picture and go a FileEntry Object

If you desire to do something similar copy the paradigm to some other location, or upload it somewhere using the FileTransfer plugin, you demand to become a FileEntry object for the returned picture. To do that, phone call window.resolveLocalFileSystemURL on the file URI returned by the Camera app. If y'all need to use a FileEntry object, set the destinationType to Camera.DestinationType.FILE_URI in your CameraOptions object (this is also the default value).

Note Yous need the File plugin to call window.resolveLocalFileSystemURL.

Hither is the phone call to window.resolveLocalFileSystemURL. The image URI is passed to this function from the success callback of getPicture. The success handler of resolveLocalFileSystemURL receives the FileEntry object.

                          function              getFileEntry              (              imgUri              )              {              window              .              resolveLocalFileSystemURL              (              imgUri              ,              function              success              (              fileEntry              )              {              // Practise something with the FileEntry object, like write to it, upload information technology, etc.              // writeFile(fileEntry, imgUri);              panel              .              log              (              "              got file:                            "              +              fileEntry              .              fullPath              );              // displayFileData(fileEntry.nativeURL, "Native URL");              },              function              ()              {              // If don't get the FileEntry (which may happen when testing              // on some emulators), re-create to a new FileEntry.              createNewFileEntry              (              imgUri              );              });              }                      

In the example shown in the preceding lawmaking, you phone call the app's createNewFileEntry part if you don't go a valid FileEntry object. The epitome URI returned from the Camera app should event in a valid FileEntry, merely platform behavior on some emulators may be dissimilar for files returned from the file picker.

Note To run into an case of writing to a FileEntry, see the File plugin README.

The code shown hither creates a file in your app's cache (in sandboxed storage) named tempFile.jpeg. With the new FileEntry object, you tin copy the image to the file or do something else like upload it.

                          function              createNewFileEntry              (              imgUri              )              {              window              .              resolveLocalFileSystemURL              (              cordova              .              file              .              cacheDirectory              ,              role              success              (              dirEntry              )              {              // JPEG file              dirEntry              .              getFile              (              "              tempFile.jpeg              "              ,              {              create              :              true              ,              sectional              :              false              },              function              (              fileEntry              )              {              // Practise something with it, like write to information technology, upload it, etc.              // writeFile(fileEntry, imgUri);              panel              .              log              (              "              got file:                            "              +              fileEntry              .              fullPath              );              // displayFileData(fileEntry.fullPath, "File copied to");              },              onErrorCreateFile              );              },              onErrorResolveUrl              );              }                      

wagnerhoper1981.blogspot.com

Source: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/

0 Response to "Why Does My Photo Rotate When I Upload It Sencha Cordova Camera Lugin"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel