Phonegap-Guardar imagen de url en la galería de fotos del dispositivo


Estoy desarrollando la aplicación phonegap y necesito guardar la Imagen de la url en la Galería de Fotos del Dispositivo.

No puedo encontrar en la Api de Phonegap una manera de hacerlo y tampoco encontré el complemento de phonegap para eso.

Lo necesito para trabajar con Iphone y Android

Muchas Gracias!

Author: michaelbn, 2014-02-05

9 answers

Este es el código de descarga de archivos que puede ser utilizado por cualquier persona. Solo tienes tres parámetros para usar esto como -

1) URL

2) Nombre de la carpeta que desea crear en su tarjeta Sd

3) Nombre del archivo (Puede dar cualquier nombre al archivo)

Todos los tipos de archivos se pueden descargar utilizando este código. puedes usar esto como .js Y esto funciona en IOS también.

//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
    }
  }
}

/ / Segundo paso para obtener el permiso de escritura y la carpeta Creación

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

/ / Tercer paso para descargar un archivo en la carpeta creada

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

Enlace Útil

 33
Author: Suhas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-25 08:01:00

La última versión de Cordova (3.3+), la versión más reciente (1.0.0+) del archivo utiliza las URL del sistema de archivos en lugar de la ruta del archivo. Por lo tanto, para hacer que la respuesta aceptada funcione con la versión más reciente de la función FileSystemSuccess cambie la línea:

var fp = rootdir.fullPath; 

A:

var fp = rootdir.toURL(); 
 17
Author: Gian Luca Scoccia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:16

Otra forma fácil es usar el plugin Cordova/Phonegap Canvas2ImagePlugin. Instalarlo y añadir la siguiente función a su código que se basa en getImageDataURL () por Raúl Sánchez (Gracias!).

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

Úsalo así:

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

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

saveImageToPhone('myimage.jpg', success, error);
 8
Author: M165437,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-04 19:38:27

Esto se puede hacer usando phone gap file plugin:

 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=="
            }
        }
    );
 6
Author: Hazem Hagrass,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-05 12:28:47

Tal vez podrías probar el plugin que escribí para IOS

Aquí está el enlace de git: https://github.com/Nomia/ImgDownloader

Breve ejemplo:

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'

También puede guardar un archivo local en la galería de imágenes utilizando el método download

 4
Author: Nimbosa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-07 07:44:59

El enfoque más simple

Si está de acuerdo con que esté en la carpeta de descarga, haga lo siguiente

  1. Instalar el complemento del navegador en la aplicación

    cordova plugin add cordova-plugin-inappbrowser
    
  2. Crea un botón de descarga con

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

Esto no solo descargará la imagen sino que ofrecerá abrir la imagen en la aplicación o navegador correspondiente.

 3
Author: aWebDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-21 06:25:23

Actualmente estoy trabajando en cordova-plugin-photo-library.

Puede guardar la imagen dada por url (file:// o data:). Funciona en ios y android, jpeg / png / gif:

cordova.plugins.photoLibrary.saveImage(url, 'My album', function () {}, function (err) {});
 2
Author: viskin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 19:39:50

Inicialmente obtuve "Could not create target file".

Para eso use encodeURI() en la url a descargar:

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

Y el código en este hilo funcionó perfectamente. Sólo lo pongo aquí.

 0
Author: allwynmasc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:16

Limpié y envolví el código sugerido por Suhas anteriormente-la respuesta aceptada en un servicio angular para que pueda usarse fácilmente en otra aplicación. Puedes encontrar el snipet aquí.

Para usarlo, incluya el script en la aplicación.js (y su índice.archivo html) entonces:

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);
            }
        });
    }
});
 0
Author: Tomer Cagan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:18