首页 文章

Phonegap - 将图像从网址保存到设备照片库中

提问于
浏览
23

我正在开发phonegap应用程序,我需要将图像从URL保存到设备照片库 .

我在Phonegap Api上找不到这样做的方法,而且我没有为此找到phonegap插件 .

我需要它与Iphone和Android合作

非常感谢!

9 回答

  • 17

    这是任何人都可以使用的文件下载代码 . 你只需要三个参数来使用它 -

    1) URL

    2) Folder name 您要在Sdcard中创建

    3) File name (你可以给文件命名)

    所有类型的文件都可以使用此代码下载 . 你可以使用它作为.js这也适用于 IOS .

    //First step check parameters mismatch and checking network connection if available call    download function
    function DownloadFile(URL, Folder_Name, File_Name) {
    //Parameters mismatch check
    if (URL == null && Folder_Name == null && File_Name == null) {
        return;
    }
    else {
        //checking Internet connection availablity
        var networkState = navigator.connection.type;
        if (networkState == Connection.NONE) {
            return;
        } else {
            download(URL, Folder_Name, File_Name); //If available download function call
        }
      }
    }
    

    //获取写入权限和文件夹创建的第二步

    function download(URL, Folder_Name, File_Name) {
    //step to request a file system 
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
    
    function fileSystemSuccess(fileSystem) {
        var download_link = encodeURI(URL);
        ext = download_link.substr(download_link.lastIndexOf('.') + 1); //Get extension of URL
    
        var directoryEntry = fileSystem.root; // to get root path of directory
        directoryEntry.getDirectory(Folder_Name, { create: true, exclusive: false }, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
        var rootdir = fileSystem.root;
        var fp = rootdir.fullPath; // Returns Fulpath of local directory
    
        fp = fp + "/" + Folder_Name + "/" + File_Name + "." + ext; // fullpath and name of the file which we want to give
        // download function call
        filetransfer(download_link, fp);
    }
    
    function onDirectorySuccess(parent) {
        // Directory created successfuly
    }
    
    function onDirectoryFail(error) {
        //Error while creating directory
        alert("Unable to create new directory: " + error.code);
    }
    
      function fileSystemFail(evt) {
        //Unable to access file system
        alert(evt.target.error.code);
     }
    }
    

    //将文件下载到创建文件夹的第三步

    function filetransfer(download_link, fp) {
    var fileTransfer = new FileTransfer();
    // File download function with URL and local path
    fileTransfer.download(download_link, fp,
                        function (entry) {
                            alert("download complete: " + entry.fullPath);
                        },
                     function (error) {
                         //Download abort errors or download failed errors
                         alert("download error source " + error.source);
                         //alert("download error target " + error.target);
                         //alert("upload error code" + error.code);
                     }
                );
    }
    

    Useful Link

  • 0

    最新版本的Cordova(3.3),较新的(1.0.0)版本的File使用文件系统URL而不是文件路径 . 因此,要使accepted answer与FileSystemSuccess函数中的较新版本一起使用,请更改以下行:

    var fp = rootdir.fullPath;
    

    至:

    var fp = rootdir.toURL();
    
  • 0

    另一种简单的方法是使用Cordova / Phonegap插件Canvas2ImagePlugin . 安装它并将以下函数添加到您的代码中,该函数基于Raul Sanchez的getImageDataURL()(谢谢!) .

    function saveImageToPhone(url, success, error) {
        var canvas, context, imageDataUrl, imageData;
        var img = new Image();
        img.onload = function() {
            canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            context = canvas.getContext('2d');
            context.drawImage(img, 0, 0);
            try {
                imageDataUrl = canvas.toDataURL('image/jpeg', 1.0);
                imageData = imageDataUrl.replace(/data:image\/jpeg;base64,/, '');
                cordova.exec(
                    success,
                    error,
                    'Canvas2ImagePlugin',
                    'saveImageDataToLibrary',
                    [imageData]
                );
            }
            catch(e) {
                error(e.message);
            }
        };
        try {
            img.src = url;
        }
        catch(e) {
            error(e.message);
        }
    }
    

    像这样使用它:

    var success = function(msg){
        console.info(msg);
    };
    
    var error = function(err){
        console.error(err);
    };
    
    saveImageToPhone('myimage.jpg', success, error);
    
  • 6

    这可以使用手机间隙file插件完成:

    var url = 'http://image_url';
        var filePath = 'local/path/to/your/file';
        var fileTransfer = new FileTransfer();
        var uri = encodeURI(url);
    
        fileTransfer.download(
            uri,
            filePath,
            function(entry) {
                console.log("download complete: " + entry.fullPath);
            },
            function(error) {
                console.log("download error source " + error.source);
                console.log("download error target " + error.target);
                console.log("upload error code" + error.code);
            },
            false,
            {
                headers: {
                    "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
                }
            }
        );
    
  • 2

    也许你可以试试我为IOS写的插件

    这是git链接:https://github.com/Nomia/ImgDownloader

    简短示例:

    document.addEventListener("deviceready",onDeviceReady);
    
    //google logo url
    url = 'https://www.google.com/images/srpr/logo11w.png';
    
    onDeviceReady = function(){
        cordova.plugins.imgDownloader.downloadWithUrl(url,function(){
            alert("success");
        },function(){
            alert("error");
        });        
    }
    
    //also you can try dataUri like: 1px gif
    //url = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
    

    您还可以使用 download 方法将本地文件保存到图库

  • 34

    Simplest approach

    如果你对它在下载的文件夹中没问题,请执行以下操作

    • 安装应用程序内浏览器插件
    cordova plugin add cordova-plugin-inappbrowser
    
    • 创建下载按钮
    onclick="window.open("Image_URL", '_system');
    

    这不仅会下载它将提供的图像,以在相应的应用程序或浏览器中打开图像 .

  • 8

    我目前正致力于cordova-plugin-photo-library .

    它可以保存url(file://或data :)给出的图像 . 适用于ios和android,jpeg / png / gif:

    cordova.plugins.photoLibrary.saveImage(url, 'My album', function () {}, function (err) {});
    
  • 4

    我最初得到 "Could not create target file" .

    为此,请在网址上下载 encodeURI()

    var DBuri = encodeURI("https://dl.dropbox.com/u/13253550/db02.xml");
    fileTransfer.download(
        DBuri,
    sPath + "database.xml",
    

    代码in this thread工作得很好 . 把它放在这里 .

  • 3

    我清理并在角度服务中包装建议的代码by Suhas above - the accepted answer,以便它可以很容易地在其他应用程序中使用 . 你可以找到snipet here .

    要使用它,请在app.js(和index.html文件)中包含脚本,然后:

    angular.module('myApp.controllers.whatever', [])
        .controller('WhateverController', function ($scope, SaveToGalleryService) {
    
        $scope.savePhoto = function(photoUrl, folderName, fileName, callback) {
            var fileName = new Date().getTime();
            SaveToGalleryService.saveToGallery(photoUrl, "Kiddiz.me", fileName, function saveSuccess(res) {
                console.log("Photo ", photoUrl, "photo saved", res);
                if (callback) {
                    callback(true, res);
                }
            }, function saveFail () {
                console.log("Photo ", photoUrl, "failed to save photo");
                if (callback) {
                    callback(false);
                }
            });
        }
    });
    

相关问题