You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Phonegap相机插件获取临时缓存图片后如何获取永久imageURI?

Hey there! I see you're running into the common issue where temporary image URIs from the PhoneGap Camera plugin get cleaned up by the system over time. Since you already have saveToPhotoAlbum: true enabled, we have a couple solid options to get persistent image URIs that won't disappear. Let's break them down:

Option 1: Copy the Image to Your App's Persistent Storage Directory

This method takes the temporary image from the cache and copies it to a private, system-protected directory that won't be automatically cleaned up. We'll use the cordova-plugin-file for this.

First, install the required plugin:

cordova plugin add cordova-plugin-file

Then modify your onSuccess function to handle the file copy:

$('.photo').click(function() {
    navigator.camera.getPicture(onSuccess, onFail, {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        saveToPhotoAlbum: true
    });

    function onSuccess(imageURI) {
        // Resolve the temporary file entry from the camera
        window.resolveLocalFileSystemURL(imageURI, function(tempFileEntry) {
            // Access your app's persistent data directory
            window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(persistentDir) {
                // Generate a unique filename to avoid overwriting existing photos
                var fileName = "persistent_photo_" + Date.now() + ".jpg";
                
                // Copy the temp file to the persistent directory
                tempFileEntry.copyTo(persistentDir, fileName, function(newFileEntry) {
                    var persistentImageURI = newFileEntry.toURL();
                    
                    // Update your UI and save the permanent URI to localStorage
                    $.mobile.changePage("#four", { transition: "slide", reverse: true, changeHash: false});
                    $('img').remove();
                    var img = $('<img />');
                    img.attr('src', persistentImageURI);
                    img.attr('width', "200");
                    img.attr('height', "200");
                    img.appendTo('#photos');
                    
                    // Save to localStorage array
                    var savedPhotos = JSON.parse(localStorage.getItem('photos')) || [];
                    savedPhotos.push(persistentImageURI);
                    localStorage.setItem('photos', JSON.stringify(savedPhotos));
                }, function(copyError) {
                    console.error("Failed to copy file: ", copyError);
                });
            }, function(dirError) {
                console.error("Failed to access persistent directory: ", dirError);
            });
        }, function(fileError) {
            console.error("Failed to resolve temp file URI: ", fileError);
        });
    }

    function onFail(message) {
        console.log('Camera failed because: ' + message);
    }
});

The cordova.file.dataDirectory is a private space for your app—files here won't be deleted unless your app is uninstalled.

Option 2: Retrieve the Permanent URI from the Photo Album

Since you're already saving photos to the system album, you can fetch the permanent URI directly from the photo library using the cordova-plugin-photo-library plugin. This avoids duplicating files, but note that users could delete the photo from their album later, breaking the URI.

First, install the plugin:

cordova plugin add cordova-plugin-photo-library

Then update your onSuccess function to fetch the latest photo from the album:

$('.photo').click(function() {
    navigator.camera.getPicture(onSuccess, onFail, {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        saveToPhotoAlbum: true
    });

    function onSuccess(imageURI) {
        // Fetch the most recently added photo from the library
        window.PhotoLibrary.getPhotos({
            limit: 1,
            sortBy: 'creationDate',
            sortOrder: 'desc'
        }, function(photos) {
            if (photos.length > 0) {
                var albumImageURI = photos[0].photoURL;
                
                // Update UI and save the album URI to localStorage
                $.mobile.changePage("#four", { transition: "slide", reverse: true, changeHash: false});
                $('img').remove();
                var img = $('<img />');
                img.attr('src', albumImageURI);
                img.attr('width', "200");
                img.attr('height', "200");
                img.appendTo('#photos');
                
                // Save to localStorage array
                var savedPhotos = JSON.parse(localStorage.getItem('photos')) || [];
                savedPhotos.push(albumImageURI);
                localStorage.setItem('photos', JSON.stringify(savedPhotos));
            }
        }, function(libraryError) {
            console.error("Failed to fetch photo from library: ", libraryError);
        });
    }

    function onFail(message) {
        console.log('Camera failed because: ' + message);
    }
});

Key Notes:

  • Permissions: Both plugins require proper permissions. For iOS, add NSPhotoLibraryUsageDescription to your config.xml; for Android, ensure you have READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE permissions configured.
  • Tradeoffs: Option 1 keeps files under your app's control but uses more storage. Option 2 saves space but relies on users not deleting the photo from their album.

内容的提问来源于stack exchange,提问作者J.Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:34:53