简体   繁体   中英

Save a web photo to camera roll in Phonegap

My iOS PhoneGap app displays a photo gallery (loaded from the server). Is it possible to add a button on an images page which saves the image to the iOS camera roll ? (similar to the tap and hold in mobile safari)

If this is something that needs to be done as a plug in, any information pointing me in the right direction would be appreciated! (My skills in obj C are very lacking).

Thanks!

It's possible with the help of the Cordova/Phonegap plugin Canvas2ImagePlugin . Install it and add the following function to your code. It's 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM