在本地存储中保存图片(PhoneGap)

15
我对phonegap很新,它有一个捕获功能。因此,我使用了它,并且非常好用。但是,我将图片显示在html中,但不知道如何保存图片。
根据http://docs.phonegap.com/en/1.7.0/cordova_camera_camera.md.html
你可以随心所欲地使用编码后的图像或URI,例如:
在标签中呈现图像(见下面的示例) 将数据本地保存(LocalStorage、Lawnchair等) 将数据发布到远程服务器
不幸的是,没有关于如何执行此操作的示例代码。
如何在LocalStorage或设备的相册中保存图像?

1
找到了 https://github.com/raananw/PhoneGap-Image-Resizer 这个项目,它还能用吗? - jhdj
它可以工作,只需要一些微调。 - jhdj
2个回答

23

太好了,你找到了解决办法,我是这样做的。 希望能对其他人有帮助。

只需在按钮点击事件中调用capturePhoto函数即可。

// A button will call this function
//
function capturePhoto() {
    sessionStorage.removeItem('imagepath');
    // Take picture using device camera and retrieve image as base64-encoded string
    navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}

function onPhotoDataSuccess(imageURI) { 
        // Uncomment to view the base64 encoded image data
        // console.log(imageData);

        // Get image handle
        //
        var imgProfile = document.getElementById('imgProfile');

        // Show the captured photo
        // The inline CSS rules are used to resize the image
        //
        imgProfile.src = imageURI;
        if(sessionStorage.isprofileimage==1){
            getLocation();
        }
        movePic(imageURI);
}

// Called if something bad happens.
// 
function onFail(message) {
    alert('Failed 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 = "MyAppFolder";

    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) {
    //Store imagepath in session for future use
    // like to store it in database
    sessionStorage.setItem('imagepath', entry.fullPath);
}

function resOnError(error) {
    alert(error.code);
}

这段代码的作用是:捕获图像并将其存储在设备SD卡的中,并将存储在会话中以便将其插入到本地数据库中。

我能够捕获图像,但无法保存到本地存储。 - Sonia John Kavery
这段代码已经由我进行了充分的测试。尝试进行调试,日志中有什么信息吗?你是否遇到了任何错误? - Amol Chakane

9

将选项中的saveToPhotoAlbum设置为True也可以很好地工作。这个提示来自于2.9文档这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接