Android Phonegap - 将图像从 url 保存到设备照片库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21577230/
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-20 04:46:10  来源:igfitidea点击:

Phonegap - Save image from url into device photo gallery

javascriptandroidioscordovaphonegap-plugins

提问by justtal

I'm developing phonegap application and I need to save Image from url to the Device Photo Gallery.

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

I can't find at the Phonegap Api a way for doing it and Also I didn't find phonegap plugin for that.

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

I need it to work with Iphone & Android

我需要它与 Iphone 和 Android 配合使用

Thanks a lot!

非常感谢!

回答by Suhas

This is file download code which can be used by anyone. You just have three parameters to use this like-

这是任何人都可以使用的文件下载代码。你只有三个参数来使用这个像 -

1) URL

1)网址

2) Folder namewhich you want to create in your Sdcard

2)要在 Sdcard 中创建的文件夹名称

3) File name(You can give any name to file)

3)文件名(你可以给文件起任何名字)

All types of file can download by using this code. you can use this as .js And this works on IOSalso.

所有类型的文件都可以使用此代码下载。您可以将其用作 .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
    }
  }
}

//Second step to get Write permission and Folder Creation

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

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);
 }
}

//Third step for download a file into created folder

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

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

有用的链接

回答by Gian Luca Scoccia

The latest version of Cordova (3.3+), the newer (1.0.0+) version of File uses filesystem URLs instead of the file path. So, to make the accepted answerwork with the newer version in the FileSystemSuccess function change the line:

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

var fp = rootdir.fullPath; 

to:

到:

var fp = rootdir.toURL(); 

回答by M165437

Another easy way is to use the Cordova/Phonegap plugin Canvas2ImagePlugin. Install it and add the following function to your code which is based on getImageDataURL()by Raul Sanchez (Thanks!).

另一种简单的方法是使用 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);
    }
}

Use it like this:

像这样使用它:

var success = function(msg){
    console.info(msg);
};

var error = function(err){
    console.error(err);
};

saveImageToPhone('myimage.jpg', success, error);

回答by Hazem Hagrass

This can be done using phone gap fileplugin:

这可以使用电话间隙文件插件来完成:

 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=="
            }
        }
    );

回答by Nimbosa

Maybe you could try the plugin I wrote for IOS

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

here is the git link: https://github.com/Nomia/ImgDownloader

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

Short Example:

简短示例:

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'

you can also save a local file to image gallery use the downloadmethod

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

回答by aWebDeveloper

Simplest approach

最简单的方法

If you are ok with it being in the download's folder do the following

如果您认为它位于下载文件夹中,请执行以下操作

  1. Install In-App browser plugin

    cordova plugin add cordova-plugin-inappbrowser
    
  2. Create a download button with

    onclick="window.open("Image_URL", '_system');
    
  1. 安装应用内浏览器插件

    cordova plugin add cordova-plugin-inappbrowser
    
  2. 创建一个下载按钮

    onclick="window.open("Image_URL", '_system');
    

Not only will this download the image it will offer to open the image in the corresponding app or browser.

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

回答by viskin

I'm currently working on cordova-plugin-photo-library.

我目前正在研究cordova-plugin-photo-library

It can save image that given by url (file:// or data:). Works on ios and android, jpeg/png/gif:

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

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

回答by Tomer Cagan

I cleaned-up and wrapped the code suggested by Suhas above - the accepted answerin an angular service so that it can easily be used in other application. You can find the snipet here.

我清理并包装了上面 Suhas建议的代码-角度服务中接受的答案,以便它可以轻松地用于其他应用程序。你可以在这里找到 snipet 。

To use it, you include the script in app.js (and your index.html file) then:

要使用它,您需要在 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);
            }
        });
    }
});

回答by allwynmasc

I initially got "Could not create target file".

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

For that use encodeURI()on the url to download:

对于encodeURI()在 url 上使用下载:

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

And the code in this threadworked perfectly. Just putting it out here.

并且此线程中的代码运行良好。放在这里就行了。