How to use the camera and gallery with Phonegap

- Andrés Cruz

En español
How to use the camera and gallery with Phonegap

In this entry we will see how to use the camera of a device with PhoneGap and also how to select a photo or image that we have on our device using the gallery provided by the operating system itself or installed from the application store manually by the user and paint the image or photograph in an img element.

Why use PhoneGap to use the device's camera and not native JavaScript / HTML5?

We might ask ourselves why use PhoneGap if we can do the same operation without using PhoneGap with native JavaScript code; The reason for this is that many times this type of operations are developing technologies, it does not have great support with browsers, or it is very recent or each browser handles the named one in its operations and that is why we use PhoneGap that allows us to use this technology in a unified manner without worrying about these previous statements.

We already explained in a previous post how to get started with Adobe PhoneGap on Windows and Android where we explained how to install PhoneGap on Windows and the testing tool on Android; Therefore we go directly to the development of the little experiment.

If we follow the above tutorial, then you don't need to install the cordova-plugin-camera

Taking the photo from the device and using the gallery application

Without going any further, we will create some functions that will allow us to do what we want, which is to select a photo from the gallery or take a photo through the device's camera, although they are different processes, for the purposes of the application they are very similar, since in both cases it is based on obtaining an image, whether it is the product of a photograph or the selection of an image from the gallery; we first define the main function of our JavaScript project:

cargarFoto: function(pictureSourceType){
        var options = {
                sourceType: pictureSourceType,
                destinationType: Camera.DestinationType.FILE_URI,
                targetWidth: 300,
                targetHeight: 300,
                correctOrientation: true,
                saveToPhotoAlbum: true,
                cameraDirection: 1,
        };, app.errorAlTomarFoto,options)

The getPicture() function allows you to take photographs through one of the cameras that the device has or select photographs from the gallery application that the device has; The function receives three parameters consisting of a function when the upload of the photo or image was successful, the next parameter when an error occurred in the upload and the last or third parameter corresponds to a group of options that we specify below:

  • sourceType Allows you to specify the type of source of the image, as specified in the title of this entry, it can be through the device's camera or through the selection of the image through the gallery.
  • destinationType Configured with Camera.DestinationType.FILE_URI allows us to indicate that it copies the image to the device and in this way when processing the image, whether as a result of the
  • selection in the gallery or the photograph taken, it returns a URI that we process from the JavaScript
  • targetWidth Indicates the scaling (width) of the image in pixels.
  • targetHeight Indicates the scaling (length) of the image in pixels.
  • quality The quality of the image expressed in a range of 0-100.
  • correctOrientationRotates the image based on the rotation of the device when the photo was taken.
  • saveToPhotoAlbum Indicates whether the photo is recorded within the device.

Once the photograph has been taken or selected, if no error occurs, the following function is executed:

fotoCargada: function(imageURI){ var img = document.createElement('img'); img.onload = function(){ app.pintarFoto(img) } img.src=imageURI },

This is already optional, but in this method we must perform some operation with the loaded image, in this case we limit ourselves to creating an img type element from JavaScript to then include the URI product of the selection or taking of the photo.

We also specify a method in case an error occurs:

errorAlTomarFoto: function(message){        console.log('Fallo al tomar la foto o toma candelada: '+message); },

Finally, we create the onclick events of a couple of buttons depending on the action the user wants to perform, that is, taking a photo or selecting an image from the gallery:

var buttonAction = document.querySelector('#button-action'); buttonAction.addEventListener('click', function(){ app.cargarFoto(Camera.PictureSourceType.CAMERA)}); var buttonGallery = document.querySelector('#button-gallery'); buttonGallery.addEventListener('click', function(){ app.cargarFoto(Camera.PictureSourceType.PHOTOLIBRARY)});

For this we simply have to change the properties

  • Camera.PictureSourceType.CAMERA Takes a photo from the device's camera.
  • Camera.PictureSourceType.PHOTOLIBRARY Open the device's gallery application to select the image.

The HTML code for this experiment is as follows:

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
    <!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />


    <div class="header">

    <canvas id="foto"></canvas>

    <div class="button-container">
        <button id="button-action" class="button">Tomar Foto</button>
        <button id="button-gallery" class="button">Imagen de Galería</button>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/camera.js"></script>


Where camera.js represents all the JavaScript code explained in this post.

The official documentation can be found at the following link: Cordova

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.