Reputation: 504
Is there a way to download and save photo from URL to album/cameraroll in iOs using Cordova?
I used FileTransfer to download photos, but they don't show up like in android gallery. I guess there should be some plugin for that, but i cant find one. Or some other method perhaps?
If it can't be done in Cordova, can be it done at all, so I could create plugin for Cordova in Objective C?
Upvotes: 0
Views: 1842
Reputation: 504
@WillCo solution probably would do the job, but creating canvas and converting canvas date do base64 to achive goal as simple as of downloading a photo seems unnecessary at least.
I recently dug up my old code of this project. I created a little native plugin for iOS that could download the image directly from the given URL to the system gallery on the device.
I posted my solution to GitHub: https://github.com/Kocik/cordova-photo-to-album-plugin
How it works:
Install plugin:
cordova plugin add https://github.com/Kocik/cordova-photo-to-album-plugin/
In your javascript add: window.plugins.phototoalbum.download(url, successCallback, failCallback);
Upvotes: 0
Reputation: 41
You will need to install Canvas2Image with your CLI like so:
cordova plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git
(or replace 'cordova' with 'phonegap' if you use that instead.)
Next, you will need to add a function (in this case saveImageToPhone()) that calls the plugin you just added to your project. This function will be called from your button selector. For instance:
<button onclick="saveMyPic("path/to/my/pic.jpg")">Save a pic to library</button>
It doesn't have to be a button, obviously, you can just make the function call and pass it any URL you like. This 'URL' can be the path that you get back from the FileTransfer success.
Here's my code:
function saveMyPic(myURL){
var MEsuccess = function(msg){
console.info(msg);
};
var MEerror = function(err){
console.error(err);
};
saveImageToPhone(myURL, MEsuccess, MEerror);
}
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);
}
} Now just call the first function from wherever you wish. If it works, you'll get a console.log that says
IMAGE SAVED!
I hope that helps you out!
Upvotes: 1