PhoneGap:将图像从画布保存到本地图像库?

时间:2014-04-04 00:01:02

标签: javascript android ios cordova

我在Android / iOS上运行了PhoneGap / Cordova应用程序。该应用程序在HTML5画布元素中创建一个图像。此画布在浏览器中导出为图像。

如何将浏览器中生成的图像保存到Android / iOS本地图库?

1 个答案:

答案 0 :(得分:0)

请尝试使用iOS Canvas2ImagePlugin的自定义插件。这将把图像从phonegap传递给native(Objective C)。将图像保存到相册

在您的iOs项目中添加2个文件SaveToPhotoAlbum.h和SaveToPhotoAlbum.m

SaveToPhotoAlbum.h

#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>


@interface SaveToPhotoAlbum : CDVPlugin {
}

- (void) saveToPhotoAlbum:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;

@end

<强> SaveToPhotoAlbum.m

#import "SaveToPhotoAlbum.h"

@implementation SaveToPhotoAlbum

- (void) saveToPhotoAlbum:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
    NSString* callbackId = [arguments pop];
    NSString* path = [arguments objectAtIndex:0];

    path = [(NSString *)path stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    path = [path stringByReplacingOccurrencesOfString:@"file://" withString:@""];

    UIImage *image = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];

    //Now it will do this for each photo in the array
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self writeJavascript: [pluginResult toSuccessCallbackString:callbackId]];
}

@end

<强> saveToPhotoAlbum.js

(function(cordova) {

/**
 * Constructor
 */
function SaveToPhotoAlbum() {}


SaveToPhotoAlbum.prototype.saveToPhotoAlbum = function(successCallback, failCallback, uri) {
    console.log('SaveToPhotoAlbum.js: saveToPhotoAlbum: uri:' + uri);
    if (!uri) {
        if (typeof failCallback === 'function') {
            failCallback('uri not provided');
        }
        return;
    }

    cordova.exec(
        successCallback,
        failCallback,
        "SaveToPhotoAlbum",
        "saveToPhotoAlbum",
        [uri]
    );
};

/**
 * Install function
 */
SaveToPhotoAlbum.install = function() {
    if ( !window.plugins ) {
        window.plugins = {};
    } 
    if ( !window.plugins.SaveToPhotoAlbum ) {
        window.plugins.SaveToPhotoAlbum = new SaveToPhotoAlbum();
    }
};

/**
 * Add to Cordova constructor
 */
if (cordova && cordova.addConstructor) {
    cordova.addConstructor(SaveToPhotoAlbum.install);
} else {
    console.log("SaveToPhotoAlbum Cordova Plugin could not be installed.");
    return null;
}

})(window.PhoneGap || window.Cordova || window.cordova);

并将您的html文件调用为:

 var imageSource = $('#widgetScreen_widgetContainer [name="mobileimage_66"]')[0].src;
            window.plugins.SaveToPhotoAlbum.saveToPhotoAlbum(photoSuccess, photoFail, imageSource);