Useful tip: Save image from arbitrary web URL to disk

I was looking for a way to save an image from a web URL to the camera roll that works across iOS and Android.

I found 2 ways:
a) The file plugin of Cordova
b) the Canvas2Image plugin

a) Never really worked well for me - various issues.
b) Worked great, but it needed a canvas

I found this great routine in stack overflow that accepts an arbitrary weburl and inside the function instantiates a canvas with that image - all packed into the function so your app does not need to bother with it.

Tried it both on iOS and Android and it works great. Given that Canvas2Image works on WinPhone too, it should work there as well

Hope this helps someone:

CREDIT: http://stackoverflow.com/questions/11618266/save-a-web-photo-to-camera-roll-in-phonegap

(success and error are callbacks – define your own)

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

Make sure the plugin is installed before you try

cordova plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git
4 Likes

This just caused a major headache for me, i keep getting various of errors
The image cannot be decoded.
Cannot save… etc

faced these issues with your sample?

Nope, works fine. Hard to say unless you provide more details/code.

1 Like