Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A function that saves images to the image library on the phone with the help of Cordova/Phonegap plugin Canvas2ImagePlugin
/**
* Saves image to phone library/gallery
* with help of Cordova/Phonegap [Canvas2ImagePlugin][1]
* based on the function [getImageDataURL][2] by Raul Sanchez
*
* @param {String} url Location of the image file
* @param {Function} success Callback function
* @param {Function} error Error handler
*
* @example
* var success = function(msg){
* console.info(msg);
* };
* var error = function(err){
* console.info(err);
* };
* saveImageToPhone('myimage.jpg', success, error);
*
* [1]: https://github.com/devgeeks/Canvas2ImagePlugin
* [2]: http://appcropolis.com/blog/web-technology/javascript-encode-images-dataurl/
*/
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.