将相机拍摄的照片捕获并存储到本地数据库/PhoneGap/Cordova/iOS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10335563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:07:08  来源:igfitidea点击:

Capturing and storing a picture taken with the Camera into a local database / PhoneGap / Cordova / iOS

ioscordovacameralocal-storagephonegap-build

提问by Jér?me

I'm currently building an app for iOS using Phonegap/Cordova and jQuerymobile. The idea is to take photos with camera and store the captured image for future use. I would like to store the path/filename into my local database and to move the picture file to a persistent place in the iPhone.

我目前正在使用 Phonegap/Cordova 和 jQuerymobile 为 iOS 构建一个应用程序。这个想法是用相机拍照并存储捕获的图像以备将来使用。我想将路径/文件名存储到我的本地数据库中,并将图片文件移动到 iPhone 中的一个持久位置。

Could someone provide me with an example ?

有人可以为我提供一个例子吗?

回答by Jér?me

Ok, here is the solution.

好的,这是解决方案。

  • in the Html file

  • I have an image tag for displaying the picture taken by the camera :

  • I have a button that runs a function for taking photo : Capture Photo

  • The function to capture photo is (when the photo is taken, the scr of the 'smallImage' id is populated with the path of the photo)

    function capturePhoto() {
    // Take picture using device camera and retrieve image as base64-encoded string
        navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
    }
    
    //Callback function when the picture has been successfully taken
    function onPhotoDataSuccess(imageData) {                
        // Get image handle
        var smallImage = document.getElementById('smallImage');
    
        // Unhide image elements
        smallImage.style.display = 'block';
        smallImage.src = imageData;
    }
    
    //Callback function when the picture has not been successfully taken
    function onFail(message) {
        alert('Failed to load picture because: ' + message);
    }
    
  • Now I want to move the picture in a permanent folder and then save the link into my database :

    function movePic(file){ 
        window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError); 
    } 
    
    //Callback function when the file system uri has been resolved
    function resolveOnSuccess(entry){ 
        var d = new Date();
        var n = d.getTime();
        //new file name
        var newFileName = n + ".jpg";
        var myFolderApp = "EasyPacking";
    
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {      
        //The folder is created if doesn't exist
        fileSys.root.getDirectory( myFolderApp,
                        {create:true, exclusive: false},
                        function(directory) {
                            entry.moveTo(directory, newFileName,  successMove, resOnError);
                        },
                        resOnError);
                        },
        resOnError);
    }
    
    //Callback function when the file has been moved successfully - inserting the complete path
    function successMove(entry) {
        //I do my insert with "entry.fullPath" as for the path
    }
    
    function resOnError(error) {
        alert(error.code);
    }
    
  • My file has been saved in the database to display it, i put "file://" front of the row that contains the image src

  • 在 Html 文件中

  • 我有一个用于显示相机拍摄的图片的图像标签:

  • 我有一个按钮可以运行拍照功能:捕获照片

  • 拍照功能是(拍照时,'smallImage' id的scr填充照片的路径)

    function capturePhoto() {
    // Take picture using device camera and retrieve image as base64-encoded string
        navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
    }
    
    //Callback function when the picture has been successfully taken
    function onPhotoDataSuccess(imageData) {                
        // Get image handle
        var smallImage = document.getElementById('smallImage');
    
        // Unhide image elements
        smallImage.style.display = 'block';
        smallImage.src = imageData;
    }
    
    //Callback function when the picture has not been successfully taken
    function onFail(message) {
        alert('Failed to load picture because: ' + message);
    }
    
  • 现在我想将图片移动到一个永久文件夹中,然后将链接保存到我的数据库中:

    function movePic(file){ 
        window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError); 
    } 
    
    //Callback function when the file system uri has been resolved
    function resolveOnSuccess(entry){ 
        var d = new Date();
        var n = d.getTime();
        //new file name
        var newFileName = n + ".jpg";
        var myFolderApp = "EasyPacking";
    
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {      
        //The folder is created if doesn't exist
        fileSys.root.getDirectory( myFolderApp,
                        {create:true, exclusive: false},
                        function(directory) {
                            entry.moveTo(directory, newFileName,  successMove, resOnError);
                        },
                        resOnError);
                        },
        resOnError);
    }
    
    //Callback function when the file has been moved successfully - inserting the complete path
    function successMove(entry) {
        //I do my insert with "entry.fullPath" as for the path
    }
    
    function resOnError(error) {
        alert(error.code);
    }
    
  • 我的文件已保存在数据库中以显示它,我将“file://”放在包含图像 src 的行的前面

Hope this help. J.

希望这有帮助。J。

P.S. : - many thanks to Simon Mac Donald (http://hi.im/simonmacdonald) for his post on googledocs.

PS : - 非常感谢 Simon Mac Donald (http://hi.im/simonmacdonald) 在 googledocs 上的帖子。

回答by MothyCK

Jerome's answer works like a charm.. the only thing to point out to people when they want to use the file don't use entry.fullPath as this can sometimes cause issues, use entry.toURL() as this will give you the full path without having to add "file://" to the path as well as bypassing issues such as SD card storage..

杰罗姆的回答就像一个魅力......当人们想要使用该文件时,唯一要指出的是不要使用 entry.fullPath 因为这有时会导致问题,使用 entry.toURL() 因为这会给你完整的路径而无需在路径中添加“file://”,也可以绕过 SD 卡存储等问题。

回答by manoz

if (index == '0')
{
    var options = {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: false,
        encodingType: Camera.EncodingType.JPEG,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false,
        correctOrientation:true
    };

    $cordovaCamera.getPicture(options).then(movePic,function(imageData) {
        $rootScope.imageUpload=imageData;
    }, function(err) {
        console.error(err);
    });

    function movePic(imageData){
        console.log("move pic");
        console.log(imageData);
        window.resolveLocalFileSystemURL(imageData, resolveOnSuccess, resOnError);
    }

    function resolveOnSuccess(entry){
        console.log("resolvetosuccess");

        //new file name
        var newFileName = itemID + ".jpg";
        var myFolderApp = "ImgFolder";

        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
            console.log("folder create");

            //The folder is created if doesn't exist
            fileSys.root.getDirectory( myFolderApp,
                {create:true, exclusive: false},
                function(directory) {
                    console.log("move to file..");
                    entry.moveTo(directory, newFileName,  successMove, resOnError);
                    console.log("release");

                },
                resOnError);
        },
        resOnError);
    }

    function successMove(entry) {
        //I do my insert with "entry.fullPath" as for the path
        console.log("success");
        //this is file path, customize your path
        console.log(entry);
    }

    function resOnError(error) {
        console.log("failed");
    }

}

回答by Mr Benn

I just did a that works with promises, based on Jér?me's answer above:

基于 Jér?me 上面的回答,我刚刚做了一个适用于承诺的工作:

function moveFile(file){

    var deferred = $q.defer();

    window.resolveLocalFileSystemURL(file,
        function resolveOnSuccess(entry){

            var dateTime = moment.utc(new Date).format('YYYYMMDD_HHmmss');
            var newFileName = dateTime + ".jpg";
            var newDirectory = "photos";

            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {

                    //The folder is created if doesn't exist
                    fileSys.root.getDirectory( newDirectory,
                        {create:true, exclusive: false},
                        function(directory) {

                            entry.moveTo(directory, newFileName, function (entry) {
                                //Now we can use "entry.toURL()" for the img src
                                console.log(entry.toURL());
                                deferred.resolve(entry);

                            }, resOnError);
                        },
                        resOnError);
                },
                resOnError);
        }, resOnError);

    return deferred.promise;
}

function resOnError(error) {
    console.log('Awwww shnap!: ' + error.code);
}

回答by samkass

There are 3 steps:

有3个步骤:

  1. Get the photo. Apple has a good example for this on the iPhone dev site
  2. Get your Documents directory, like so:
    
    NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(
                NSDocumentDirectory,
                NSUserDomainMask,
                YES);
    NSString *docDir = [arrayPaths objectAtIndex:0];
    
  3. And finally, storing the UIImage you got in step 1 out to disk:
    
    NSString *filename = @"mypic.png";
    NSString *fullpath = [docDir stringByAppendingPathComponent:filename];
    [UIImagePNGRepresentation(image) writeToFile:fullpath atomically:YES];
    
  1. 得到照片。苹果在 iPhone 开发网站上有一个很好的例子
  2. 获取您的 Documents 目录,如下所示:
    
    NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(
                NSDocumentDirectory,
                NSUserDomainMask,
                YES);
    NSString *docDir = [arrayPaths objectAtIndex:0];
    
  3. 最后,存储的UIImage在步骤1中得到磁盘:
    
    NSString *filename = @"mypic.png";
    NSString *fullpath = [docDir stringByAppendingPathComponent:filename];
    [UIImagePNGRepresentation(image) writeToFile:fullpath atomically:YES];