22

Can anyone tell me, or point me in the direction of how to get an image from the phone's image gallery in Phonegap / Android? There's docs on accessing the camera (which works great) but not selecting an existing image.

I'm looking for Phonegap / Javascript rather than Java.

Thanks in advance!

logic-unit
  • 4,195
  • 12
  • 47
  • 72

6 Answers6

50

Erm, the Camera docs cover this. Is this not working for you? Check out Camera.PictureSourceType for details. The docs site givens this example for deriving an image thus:

function getPhoto(source) {
  // Retrieve image file location from specified source
  navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
    destinationType: destinationType.FILE_URI,
    sourceType: source });
}

sourceType is the crucial bit here. It can be Camera.PictureSourceType.CAMERA (the default), or more useful for you it can be Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM.

Camera Documentation

Ben
  • 7,548
  • 31
  • 45
  • 15
    Great answer but I think the phonegap docs could do with some pics. It undersells itself. It would also help people with the attention span of a fish like me :) Thank goodness for the readers of things :) – Roger Hills Dec 02 '11 at 08:35
  • What's the difference: PHOTOLIBRARY vs SAVEDPHOTOALBUM – Paranoid Android Nov 22 '17 at 23:04
  • @Mirko what it says on the tin: either the general image library on the device, or a specific album. (Note that there are quirks with these two options on certain versions of Android however). – Ben Nov 23 '17 at 08:39
  • @Ben just found the docs: `Camera.PictureSourceType.PHOTOLIBRARY and Camera.PictureSourceType.SAVEDPHOTOALBUM both display the same photo album.` so no difference. https://github.com/apache/cordova-plugin-camera – Paranoid Android Nov 23 '17 at 10:18
  • @Mirko you're referring to the current plugin. This post dates back six years, dealing with a far older instance. And back then the two were inter-changeable on certain Android versions, yes (not on iOS). – Ben Nov 23 '17 at 14:03
  • @Ben yeah, I think on Android it never made any difference. – Paranoid Android Nov 23 '17 at 14:24
5

You can also use following library: https://github.com/wymsee/cordova-imagePicker I prefer this one as it's smaller, easy to implement and does not require permission to camera.

Klapsa2503
  • 829
  • 10
  • 33
2

Take a look at this post, it may help you.

Sometimes, you may face some problem with uploading an existing image. The solution is simple, per this answer. Briefly, you need to convert the native Android URI to one that the API can use:

// URL you are trying to upload from inside gallery
window.resolveLocalFileSystemURI(img.URI, function(entry) {
  console.log(entry.fullPath);
  }, function(evt){
    console.log(evt.code);
  }
);
Community
  • 1
  • 1
T.Baba
  • 649
  • 7
  • 17
1
document.addEventListener("deviceready",function(){

            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){ 
                var sdcard = fileSystem.root;

                sdcard.getDirectory('dcim/camera',{create:false}, function(dcim){
                    var directoryReader = dcim.createReader();
                    directoryReader.readEntries(function(entries){
                       for (var i=0; i<entries.length; i++) {
                           entries[i].file(function(f){
                                 var reader = new FileReader();
                                 reader.onloadend = function (evt) {
                                 var url= evt.target.result;//base64 data uri

                                 console.log(url)
                                 reader.abort();
                             };
                             reader.readAsDataURL(f);

                           },function(error){
                               console("Unable to retrieve file properties: " + error.code);

                           });

                       }

                    },function(e){
                        console.log(e.code);
                    });


                }, function(error){
                    console.log(error.code);
                });


            }, function(evt){ // error get file system
                 console.log(evt.target.error.code);
            });



        } , true);
logic-unit
  • 4,195
  • 12
  • 47
  • 72
Jessie Han
  • 127
  • 1
  • 6
0

I'm working on cordova-plugin-photo-library plugin which provides cross-platform way to enumerate through all photos on device.

Usage:

cordova.plugins.photoLibrary.getLibrary(function (library) {
    // Here we have the library as array
    cordova.plugins.photoLibrary.getThumbnailUrl(library[0],
        function (thumbnailUrl) { image.src = thumbnailUrl; },
        function (err) { console.log('Error occured'); },
        {
            thumbnailWidth: 512,
            thumbnailHeight: 384,
            quality: 0.8
        });
    });
viskin
  • 493
  • 4
  • 15
  • Hello @viskin. Sorry to hijack but I found your plugin today, but on my phone the code at https://jsfiddle.net/kartagis/pjdqp3ku/ takes ~15 seconds. Should I use localStorage or something to speed the process? – Tolga Ozses Jan 19 '17 at 19:09
  • Please open an issue on github page of the project – viskin Jan 19 '17 at 19:24
0

Easy

First add camera plugin to the project in CMD.

F:\phonegap>myapp>cordova plugin add cordova-plugin-camera

And then Try this

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'" />
        <title>PhoneGap app</title>

        <!-- Script -->
        <script type="text/javascript" src="cordova.js" ></script>
        <script type='text/javascript' src='jquery-3.0.0.js' ></script>
        <script type='text/javascript'>
        $(document).ready(function(){

            // Take photo from camera
            $('#but_take').click(function(){
                navigator.camera.getPicture(onSuccess, onFail, { quality: 20,
                    destinationType: Camera.DestinationType.FILE_URL 
                });
            });

            // Select from gallery 
            $("#but_select").click(function(){
                navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
                    sourceType: Camera.PictureSourceType.PHOTOLIBRARY, 
                    allowEdit: true,
                    destinationType: Camera.DestinationType.FILE_URI
                });
            });

            // Change image source
            function onSuccess(imageData) {
                var image = document.getElementById('img');
                image.src = imageData + '?' + Math.random();;
            }

            function onFail(message) {
                alert('Failed because: ' + message);
            }

        });
        </script>
    </head>
    <body>
        <div style="margin:0 auto; width:30%!important;text-align: center;">
            <img src="img/cam2.jpg" id='img' style="width: 100px; height: 100px;">
        </div><br/>
        <div style="width:100%; text-align:center; padding:10px;">
            <button id='but_take'>Take photo</button>
            <button id='but_select'>Select photo from Gallery</button>
        </div>
    </body>
</html>

I'm 100% sure it works.

the reference is here Choose an image from Camera or Gallery – PhoneGap

Mohsen Molaei
  • 124
  • 1
  • 4