【发布时间】:2023-04-04 12:10:01
【问题描述】:
我有一个在 Android/iOS 上运行的 PhoneGap/Cordova 应用程序。该应用程序在 HTML5 画布元素中创建图像。此画布在浏览器中导出为图像。
如何将浏览器生成的图片保存到 Android/iOS 本地图库?
【问题讨论】:
标签: javascript android ios cordova
我有一个在 Android/iOS 上运行的 PhoneGap/Cordova 应用程序。该应用程序在 HTML5 画布元素中创建图像。此画布在浏览器中导出为图像。
如何将浏览器生成的图片保存到 Android/iOS 本地图库?
【问题讨论】:
标签: javascript android ios cordova
请尝试使用 iOS 的自定义插件 Canvas2ImagePlugin 。这会将图像从 phonegap 传递到本地(目标 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);
【讨论】: