Phonegap - Save image from url into device photo gallery

63,167

Solution 1

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

1) URL

2) Folder name which you want to create in your Sdcard

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

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

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

Solution 2

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 answer work with the newer version in the FileSystemSuccess function change the line:

var fp = rootdir.fullPath; 

to:

var fp = rootdir.toURL(); 

Solution 3

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!).

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

Solution 4

This can be done using 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=="
            }
        }
    );

Solution 5

Maybe you could try the plugin I wrote for IOS

here is the git link: 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 download method

Share:
63,167

Related videos on Youtube

justtal
Author by

justtal

Updated on July 22, 2022

Comments

  • justtal
    justtal almost 2 years

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

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

    I need it to work with Iphone & Android

    Thanks a lot!

  • justtal
    justtal about 10 years
    Thanks. But how do I know the filePath to the device gallery?
  • Hazem Hagrass
    Hazem Hagrass about 10 years
    you can save it to any folder in sdcard then it should appear automatically in your gallery :)
  • Hazem Hagrass
    Hazem Hagrass about 10 years
    Actually I'm not sure about iOS :(
  • Suhas Gosavi
    Suhas Gosavi about 10 years
    If you download image from any URL, it will appear automatically in your device gallery. Using this you can download any file by creating new folder or existing folder not only image.
  • confile
    confile about 10 years
    @HazemHagrass Does this also works if the source url is an image as data url?
  • doron
    doron about 10 years
    It doesn't work for me :(. I get an error code 1. What should I do?
  • Suhas Gosavi
    Suhas Gosavi about 10 years
    @doron which device? this should work. You are so close, it's just your target file that is wrong I think.
  • doron
    doron about 10 years
    samsung galaxy s3, android 4.1.2. what could be wrong? I used the code written here.
  • Suhas Gosavi
    Suhas Gosavi about 10 years
    @doron this should work. If you are using same code. You added file transfer plugin in config file? And you just have to provide three parameters url, folder name, file name to above code.
  • doron
    doron about 10 years
    Hi, When I add this string to the beginning of the file path: file:///storage/sdcard0 - it works. Maybe, the fileSystem.root command has some problem?
  • trainoasis
    trainoasis almost 10 years
    @doron firstly, thanks for your tip about file path, it worked for me. Secondly, did you perchance figure out how to store something to one of the folders in your app?
  • trainoasis
    trainoasis almost 10 years
    @Hazem thank you, this works, but how can I store to one of the folders inside my app? for me only file:///storage/... works
  • h3n
    h3n almost 10 years
    Gian's answer worked for me. Change the rootdir.fullPath to rootdir.toUrl();
  • Nimbosa
    Nimbosa over 9 years
    I dont know who give me a downvote, and I dont know why, but it works on IOS, easy to use. :>
  • commonpike
    commonpike over 9 years
    If you download image from any URL, it will appear automatically in your device gallery. - not for me. I can find it on my filesystem, but it doesnt appear in the gallery ?
  • commonpike
    commonpike over 9 years
    Re: commonpike - I read elsewhere the gallery has to be triggered to re-index the sdcard on android.
  • commonpike
    commonpike over 9 years
    On my end, this is the only answer that not only downloads the photo, but also inserts it into the gallery as the op requested. On android, it calls the MediaScanner intent to reindex the gallery so it shows up right away. On iOS, it requests access to the 'Photos'.
  • decodingpanda
    decodingpanda over 9 years
    stackoverflow.com/questions/3625640/… in my ansswer here, I have used fileSystem.root.nativeURL; //root path
  • commonpike
    commonpike about 9 years
    on winphone however, it throws a security error. the canvas is 'tainted' and canvas.toDataURL is not allowed; even if the server sets the correct CORS headers on the image.
  • commonpike
    commonpike about 9 years
    winphone (ie10) is discussed here - with a workaround using xhr : stackoverflow.com/questions/18112047/… .
  • Danilo Oliveira
    Danilo Oliveira about 9 years
    How can i save a Image for display in Gallery?
  • Jorge Sampayo
    Jorge Sampayo over 8 years
    I guess it was because even the plugin works, the question was very specific "to work on android and ios"
  • Adrian Marinica
    Adrian Marinica over 8 years
    I tried this for the past 2 days, but I could not save to the Photo Library of an iOS device. Instead, the images were getting saved to the app's sandbox (as the URL also suggested). To achieve saving the images in the Photo Library, I had to use cordova-plugin-canvas2image which worked like a charm. I see this answer has a lot of upvotes, so maybe the API changed in the meantime, or something like that.
  • Jane Wayne
    Jane Wayne about 8 years
    @AdrianMarinica could you please provide your solution with cordova-plugin-canvas2image? i tried the solution proposed here, but it keeps saving to the internal folder and does NOT show up in the photo gallery.
  • Jane Wayne
    Jane Wayne about 8 years
    That still does not make the image save to a location that will be picked up by the photogallery.
  • Adrian Marinica
    Adrian Marinica about 8 years
    @JaneWayne you should be able to find all the information you need here npmjs.com/package/cordova-plugin-canvas2image
  • santhosh
    santhosh almost 8 years
    will that download the image. because when i tried it was only downloading documentation like pdf.for images we have to hold the image and then it asks for save(in chrome). correct me if i'm wrong
  • aWebDeveloper
    aWebDeveloper almost 8 years
    hmmm. would show all applicable programs as handler. Ya but in most cases chrome is the one and what you said is right
  • santhosh
    santhosh almost 8 years
    is their any work around to this small problem for images??
  • J261
    J261 almost 8 years
    this work for me with a little changes. I use phonegap build: github.com/devgeeks/Canvas2ImageDemo
  • Martijn Pieters
    Martijn Pieters over 7 years
    I recommend you read How to offer personal open-source libraries? before posting about your projects here.
  • viskin
    viskin over 7 years
    I've read. The question asked was to get phonegap plugin to save to photo gallery, that works with ios and android. The answer provided a solution, with sample code to achieve what @justtal wanted. I disclosed that I'm library's author. Is really my answer looks inappropriate to you? I personally read through answers to this specific questions, and when found no solution that worked to me, implemented my project which I shared.
  • Martijn Pieters
    Martijn Pieters over 7 years
    You were posting the exact same answer, without any further customisation to the specific question, to multiple places, which is why I prompted you to read that post. Don't go seek out all the places where your library might offer a solution, please.
  • viskin
    viskin over 7 years
    Ok. See, I understand that I answer to multiple questions with same copy-paste answer, but we are talking about multiple completely identical questions. I just don't know what I can customize in my answer, maybe saying the same thing with different words? Will it be more appropriate way to post?
  • Martijn Pieters
    Martijn Pieters over 7 years
    At that point, vote to close the questions as duplicates. That's what we have that option for.
  • viskin
    viskin over 7 years
    Great, will do that.
  • JavaNoScript
    JavaNoScript almost 7 years
  • Pritish
    Pritish over 6 years
    does it support to downloaded video and display it in the gallery of ios device.
  • Pritish
    Pritish over 6 years
    @Suhas I tried this code for ios but it's not working.
  • Suhas Gosavi
    Suhas Gosavi over 6 years
    @Pritish yes working for iOS also please check if you are getting any error
  • Pritish
    Pritish over 6 years
    @Suhas I am not getting any error right now I am trying it on the emulator. do I need to test it on the real device of ios.
  • Suhas Gosavi
    Suhas Gosavi over 6 years
    @Pritish yes please check on device
  • Pritish
    Pritish over 6 years
    @Suhas on real device it show me error message alert("download error source " + error.source); here
  • Pritish
    Pritish over 6 years
    @Suhas var fp = rootdir.fullPath; in console.log it displays only / (slash).
  • Pritish
    Pritish over 6 years
    @Suhas same code running on emulator but on real device it gives error error message alert("download error source " + error.source);
  • Pritish
    Pritish over 6 years
    @HazemHagrass does it work on ios to download mp3 as well as video files.
  • Hazem Hagrass
    Hazem Hagrass over 6 years
    @Pritish I don’t think it’s working with audio files generally on iOS.
  • Julian Paolo Dayag
    Julian Paolo Dayag over 5 years
    this will freeze the UI if your are downloading large images.
  • commonpike
    commonpike over 5 years
    And as of now (2018), this just crashes on iOS. Canvas2ImagePlugin is not maintained anymore and there are issues mentioned. Android works (but only if you call it exactly as written above, using cordova.exec(..), otherwise it fails with a message)