44 Commits
1.0.0 ... 4.0.0

Author SHA1 Message Date
StefanoMagrassi
4dc72591ee version 4.0.0 2016-04-13 10:15:33 +02:00
StefanoMagrassi
1de7e2d5f5 Merge branch 'issue#4'
resolves #4
2016-04-13 10:14:24 +02:00
StefanoMagrassi
3e6b70dba7 manage default prefix only in js 2016-04-13 10:11:05 +02:00
StefanoMagrassi
42ee53b9e9 notes for options parameter in README 2016-04-13 10:09:52 +02:00
StefanoMagrassi
8177ea902e make requiring work 2016-04-13 09:09:26 +02:00
StefanoMagrassi
cbdd6cd3d1 Object.assign local polyfill 2016-04-12 17:52:05 +02:00
StefanoMagrassi
ba52ad27a7 media scanner option in camel case 2016-04-12 12:35:13 +02:00
Bastian Meier
92a9cc577b mediaScanner in camelcase 2016-04-12 12:34:17 +02:00
Bastian Meier
3d78e43388 options.medisScanner should be Camelcase 2016-04-12 12:34:06 +02:00
Bastian Meier
fff731c9e3 fix for 'mediaSanner wrong type'-bug 2016-04-12 12:27:16 +02:00
StefanoMagrassi
7afc399a3a update version -> bump version 2016-04-12 09:17:11 +02:00
StefanoMagrassi
03dc4f65bb updated documentation 2016-04-12 09:05:04 +02:00
StefanoMagrassi
87ffe30dd3 options object in base64ToGallery api 2016-04-12 09:04:44 +02:00
StefanoMagrassi
fdae1613eb run media scanner only if enabled through options 2016-04-11 17:09:55 +02:00
StefanoMagrassi
b56e720048 cleanup 2016-04-11 17:08:16 +02:00
StefanoMagrassi
8ae80d457c npm -> save exact version and show no progress bar 2016-04-11 15:31:22 +02:00
StefanoMagrassi
247413e97d Merge branch 'release-3.0.0' 2016-01-22 15:38:43 +01:00
StefanoMagrassi
9c482f9782 version 3.0.0 - fixes #3 2016-01-22 15:36:21 +01:00
StefanoMagrassi
2495048e3b Merge branch 'readme_updates' into issue#3 2016-01-22 15:32:39 +01:00
StefanoMagrassi
1384a7d8c1 readme updates for version 3.0.0 2016-01-22 15:32:26 +01:00
StefanoMagrassi
6152a9fcd2 edited to be compliant with cordova-ios > 3.8.0
- removed iVars in Base64ToGallery interface definition (compiler warning)
- callbackId and result class public property
- fixed wrong variables refencies and names
- background thread (previous commit, but it's important to notice it)
2016-01-21 12:18:17 +01:00
StefanoMagrassi
538f749c1b changed ios api 2016-01-21 11:20:50 +01:00
StefanoMagrassi
b26b55a061 Merge branch 'release-2.0.2' 2016-01-20 18:01:10 +01:00
StefanoMagrassi
bac8ff71a3 version 2.0.2 2016-01-20 18:00:59 +01:00
StefanoMagrassi
ed8a8f13d3 Merge branch 'update-version-script' 2016-01-20 17:58:34 +01:00
StefanoMagrassi
3d740e8e63 removed libxmljs and back to good ol' regex 2016-01-20 17:58:18 +01:00
StefanoMagrassi
1eb312609c Merge branch 'hotfix-gitignore' 2016-01-20 17:06:23 +01:00
StefanoMagrassi
ce3f8563c4 .log ignored 2016-01-20 17:06:13 +01:00
StefanoMagrassi
59998f3950 Merge branch 'plugin-engine-conf' 2016-01-20 17:02:20 +01:00
StefanoMagrassi
e4dfa52b05 .npmignore - leaner module 2016-01-20 17:01:25 +01:00
StefanoMagrassi
4080c64451 cordova-ios platform version
It was specified the supported version of cordova-ios platform
2016-01-20 16:59:01 +01:00
StefanoMagrassi
c744de9fb1 removed useless log messages - resolves #2 2016-01-05 12:18:53 +01:00
StefanoMagrassi
e2dcccf17e Merge branch 'issue#2' 2016-01-05 12:16:41 +01:00
StefanoMagrassi
d0f536a8b9 removed useless log messages from WP8 class 2016-01-05 12:16:00 +01:00
StefanoMagrassi
ec45e6aabb removed useless log messages from iOS class 2016-01-05 12:13:26 +01:00
StefanoMagrassi
c4009429a4 removed useless log message from Android class 2016-01-05 12:02:48 +01:00
StefanoMagrassi
a4e55d33c7 updated version - resolves #1 2015-12-18 12:39:44 +01:00
StefanoMagrassi
a6aaccb601 Merge branch 'issue#1' 2015-12-18 12:38:11 +01:00
StefanoMagrassi
0189a7b7bd Merge branch 'version_updater' into issue#1 2015-12-18 12:37:00 +01:00
StefanoMagrassi
4ca9499c95 added script to automate version update both in package.json and in plugin.xml 2015-12-18 12:36:45 +01:00
StefanoMagrassi
9182f20d32 changed repo name and plugin id 2015-12-18 12:17:02 +01:00
StefanoMagrassi
7ff985c7d7 version updated 2015-12-11 17:39:01 +01:00
StefanoMagrassi
a1fade2462 scripts fix and description changed 2015-12-11 17:38:45 +01:00
StefanoMagrassi
a2a78795b9 eslint no-console rule disabled 2015-12-11 17:35:21 +01:00
14 changed files with 370 additions and 249 deletions

View File

@@ -2,6 +2,7 @@
"extends": "eslint:recommended",
"rules":
{
"no-console": 0,
"indent": [2, 2,
{
"VariableDeclarator": 2
@@ -13,7 +14,6 @@
},
"env":
{
"node": true,
"commonjs": true
"node": true
}
}

1
.gitignore vendored
View File

@@ -1,5 +1,6 @@
# Commons
/node_modules
*.log
# OS
.DS_Store

5
.npmignore Normal file
View File

@@ -0,0 +1,5 @@
# Make NPM module leaner
/scripts
.eslintrc
.npmrc

2
.npmrc
View File

@@ -1,2 +1,4 @@
git-tag-version = false
tag-version-prefix =
save-exact = true
progress = false

View File

@@ -1,21 +1,47 @@
# Cordova base64ToGallery Plugin
This plugin (based on [devgeeks/Canvas2ImagePlugin](http://github.com/devgeeks/Canvas2ImagePlugin)) allows you to save base64 data as a png image into the device (iOS Photo Library, Android Gallery or WindowsPhone 8 Photo Album).
The plugin is a kind of fork of the [solderzzc/Base64ImageSaverPlugin](https://github.com/solderzzc/Base64ImageSaverPlugin) but with a cleaner history (a.k.a: no tags from Canvas2ImagePlugin repo).
The plugin is a kind of fork of the [solderzzc/Base64ImageSaverPlugin](https://github.com/solderzzc/Base64ImageSaverPlugin) but with a cleaner history (a.k.a: no tags from Canvas2ImagePlugin repo) and a newer iOS implementation.
## Alerts
### Plugin id - [issue #1](https://github.com/Nexxa/cordova-base64-to-gallery/issues/1)
In order to be more consistent with the cordova naming convention, since version 2.0 the repository name and the cordova plugin id have changed to **cordova-base64-to-gallery**.
Please uninstall the old version and reinstall the new one.
### cordova-ios > 3.8.0 - [issue #3](https://github.com/Nexxa/cordova-base64-to-gallery/issues/3)
According to the [documentation](https://github.com/apache/cordova-ios/blob/master/guides/API%20changes%20in%204.0.md#nsdatabase64h-removed), `NSData+Base64.h` class was removed starting from version 4.0.0 of the **cordova-ios platform** (and it was already deprecated from version 3.8.0).
So, cordova-base64-to-gallery plugin **from version 3.0.0** has changed the iOS implementation in order to support the changes in cordova-ios platform.
If you need to support cordova-ios < 3.8.0 please refer to [cordova-base64-to-gallery@2.0.2](https://github.com/Nexxa/cordova-base64-to-gallery/tree/2.0.2). There is also an "**old**" branch that might have some updates in the future (Android/WP8 fixes or something like that).
## Usage
Call the `cordova.base64ToGallery()` method using success and error callbacks and the id attribute or the element object of the canvas to save:
Call the `cordova.base64ToGallery()` method using success and error callbacks and the passing the image's base64 string (`options` is optional):
### Methods
#### `cordova.base64ToGallery(data, [prefix, success, fail])`
#### `cordova.base64ToGallery(data, [options, success, fail])`
Param | Type | Default | Description
----------- | ---------- | ----------------- | ------------------
**data** | *string* | | base64 string
**prefix** | *string* | **img_** | file's name prefix
**options** | *object* | \*see below | options
**success** | *function* | **console.log** | success callback
**fail** | *function* | **console.error** | fail callback
#### Available options *
##### `prefix`
Saved file name prefix. Only works in Android and WP8.
**Default**: "img_"
##### `mediaScanner`
Android Media Scanner after file creation enabled or not. Only works in Android.
**Default**: true
### Example
```javascript
@@ -23,13 +49,16 @@ function onDeviceReady() {
cordova.base64ToGallery(
base64Data,
'img_',
{
prefix: 'img_',
mediaScanner: true
},
function(msg){
function(msg) {
console.log(msg);
},
function(err){
function(err) {
console.error(err);
}
);

View File

@@ -1,34 +1,31 @@
{
"name": "cordova-base64-to-gallery",
"version": "1.0.0",
"description": "This plugin allows you to save base64 data as a png image into the device (iOS Photo Library, Android Gallery, WindowsPhone 8 Photo Album).",
"version": "4.0.0",
"description": "Cordova plugin to save base64 data as a png image into the device",
"license": "MIT",
"scripts":
{
"lint": "eslint www/ase64ToGallery.js",
"scripts": {
"bump": "node ./scripts/bump_version",
"lint": "eslint www/base64ToGallery.js",
"test": "npm run lint",
"prepublish": "npm test"
},
"repository":
{
"repository": {
"type": "git",
"url": "git+https://github.com/Nexxa/base64ToGallery.git"
"url": "git+https://github.com/Nexxa/cordova-base64-to-gallery.git"
},
"bugs":
{
"url": "https://github.com/Nexxa/base64ToGallery/issues"
"bugs": {
"url": "https://github.com/Nexxa/cordova-base64-to-gallery/issues"
},
"engines": [
{
"cordova": ">=3.0.0"
},
{
"node": ">=0.12 <4.0"
"node": ">=0.12"
}
],
"cordova":
{
"id": "it.nexxa.base64ToGallery",
"cordova": {
"id": "cordova-base64-to-gallery",
"platforms": [
"ios",
"android",
@@ -40,13 +37,13 @@
"base64",
"save",
"photo library",
"gallery",
"ecosystem:cordova",
"cordova-ios",
"cordova-android",
"cordova-wp8"
],
"author":
{
"author": {
"name": "StefanoMagrassi",
"email": "stefano.magrassi@gmail.com",
"url": "http://thinkwritedone.com"
@@ -58,8 +55,8 @@
"url": "http://www.tiegushi.com"
}
],
"devDependencies":
{
"eslint": "^1.10.3"
"devDependencies": {
"eslint": "1.10.3",
"nodemsg": "1.0.0"
}
}
}

View File

@@ -1,67 +1,69 @@
<plugin id="it.nexxa.base64ToGallery" version="1.0.0" xmlns:android="http://schemas.android.com/apk/res/android" xmlns="http://www.phonegap.com/ns/plugins/1.0">
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns:android="http://schemas.android.com/apk/res/android" xmlns="http://www.phonegap.com/ns/plugins/1.0" id="cordova-base64-to-gallery" version="4.0.0">
<engines>
<engine name="cordova-ios" version=">=3.8.0" />
</engines>
<name>base64ToGallery</name>
<engines>
<engine name="cordova" version=">=3.0.0" />
</engines>
<description>This plugin allows you to save base64 data as a png image into the device (iOS Photo Library, Android Gallery, WindowsPhone 8 Photo Album).</description>
<author>Tommy-Carlos Williams - tommy@devgeeks.org</author>
<author>Simba Zhang - solderzzc@gmail.com</author>
<author>StefanoMagrassi - stefano.magrassi@gmail.com</author>
<keywords>base64,png,save,canvas,image,photo library</keywords>
<description>This plugin allows you to save base64 data as a png image into the device (iOS Photo Library, Android Gallery, WindowsPhone 8 Photo Album).</description>
<author>Tommy-Carlos Williams - tommy@devgeeks.org</author>
<author>Simba Zhang - solderzzc@gmail.com</author>
<author>StefanoMagrassi - stefano.magrassi@gmail.com</author>
<keywords>base64,png,save,canvas,image,photo library</keywords>
<license>MIT</license>
<license>MIT</license>
<js-module name="object.assign-polyfill" src="www/object.assign-polyfill.js">
</js-module>
<js-module name="base64ToGallery" src="www/base64ToGallery.js">
<clobbers target="cordova.base64ToGallery"/>
</js-module>
<js-module name="base64ToGallery" src="www/base64ToGallery.js">
<clobbers target="cordova.base64ToGallery"/>
</js-module>
<!-- ios -->
<platform name="ios">
<config-file parent="/*" target="config.xml">
<feature name="Base64ToGallery">
<param name="ios-package" value="Base64ToGallery"/>
<param name="onload" value="true"/>
</feature>
</config-file>
<!-- ios -->
<platform name="ios">
<source-file compiler-flags="-fno-objc-arc" src="src/ios/Base64ToGallery.m"/>
<header-file src="src/ios/Base64ToGallery.h"/>
<config-file parent="/*" target="config.xml">
<feature name="Base64ToGallery">
<param name="ios-package" value="Base64ToGallery"/>
<param name="onload" value="true"/>
</feature>
</config-file>
<source-file compiler-flags="-fno-objc-arc" src="src/ios/Base64ToGallery.m"/>
</platform>
<header-file src="src/ios/Base64ToGallery.h"/>
</platform>
<!-- android -->
<platform name="android">
<!-- android -->
<platform name="android">
<source-file src="src/android/Base64ToGallery.java" target-dir="src/it/nexxa/Base64ToGallery"/>
<config-file parent="/*" target="AndroidManifest.xml">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</config-file>
<config-file parent="/*" target="AndroidManifest.xml">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</config-file>
<config-file parent="/*" target="res/xml/config.xml">
<feature name="Base64ToGallery">
<param name="android-package" value="it.nexxa.base64ToGallery.Base64ToGallery"/>
</feature>
</config-file>
<config-file parent="/*" target="res/xml/config.xml">
<feature name="Base64ToGallery">
<param name="android-package" value="it.nexxa.base64ToGallery.Base64ToGallery"/>
</feature>
</config-file>
</platform>
<source-file src="src/android/Base64ToGallery.java" target-dir="src/it/nexxa/Base64ToGallery"/>
<!-- wp8 -->
<platform name="wp8">
<source-file src="src/wp8/Base64ToGallery.cs"/>
</platform>
<config-file parent="/*" target="config.xml">
<feature name="Base64ToGallery">
<param name="wp-package" value="Base64ToGallery"/>
<param name="onload" value="true"/>
</feature>
</config-file>
<!-- wp8 -->
<platform name="wp8">
<config-file parent="/*" target="config.xml">
<feature name="Base64ToGallery">
<param name="wp-package" value="Base64ToGallery"/>
<param name="onload" value="true"/>
</feature>
</config-file>
<config-file parent="/Deployment/App/Capabilities" target="Properties/WMAppManifest.xml">
<Capability Name="ID_CAP_MEDIALIB_PHOTO"/>
</config-file>
<source-file src="src/wp8/Base64ToGallery.cs"/>
</platform>
</plugin>
<config-file parent="/Deployment/App/Capabilities" target="Properties/WMAppManifest.xml">
<Capability Name="ID_CAP_MEDIALIB_PHOTO"/>
</config-file>
</platform>
</plugin>

29
scripts/bump_version.js Normal file
View File

@@ -0,0 +1,29 @@
/*eslint-env node*/
// Modules
var fs = require('fs');
var logger = require('nodemsg');
var pkg = require('../package.json');
// CONSTS
var CONFIG_FILE = 'plugin.xml';
var PLUGIN_ID = 'cordova-base64-to-gallery';
var ERROR_MSG = 'No "version" attribute found - Please check '+ CONFIG_FILE +' ("version" tag must follow "id" tag)';
var REGEXP = '(id="' + PLUGIN_ID + '" )(version="\\d+[.]\\d+[.]\\d+")';
// Logic
var version = pkg.version;
var regex = new RegExp(REGEXP);
var config = fs.readFileSync(CONFIG_FILE, { encoding: 'utf8'});
// Exit if version tag not found
if (!regex.test(config)) {
logger.error(ERROR_MSG);
process.exit(1);
}
// Set version
config = config.replace(regex, '$1version="' + version + '"');
fs.writeFileSync(CONFIG_FILE, config);

View File

@@ -30,124 +30,109 @@ import android.util.Log;
*/
public class Base64ToGallery extends CordovaPlugin {
// Consts
public static final String ACTION = "saveImageDataToLibrary";
public static final String DEFAULT_FILE_PREFIX = "img_";
public static final String EMPTY_STR = "";
// Consts
public static final String EMPTY_STR = "";
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
if (action.equals(ACTION)) {
String base64 = args.optString(0);
String filePrefix = args.optString(1);
boolean mediaScannerEnabled = args.optBoolean(2);
String base64 = args.optString(0);
String filePrefix = args.optString(1);
// isEmpty() requires API level 9
if (base64.equals(EMPTY_STR)) {
callbackContext.error("Missing base64 string");
}
// isEmpty() requires API level 9
if (base64.equals(EMPTY_STR)) {
callbackContext.error("Missing base64 string");
}
// Create the bitmap from the base64 string
byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (filePrefix.equals(EMPTY_STR)) {
filePrefix = DEFAULT_FILE_PREFIX;
}
if (bmp == null) {
callbackContext.error("The image could not be decoded");
// Create the bitmap from the base64 string
Log.d("Base64ToGallery", base64);
} else {
byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
// Save the image
File imageFile = savePhoto(bmp, filePrefix);
if (bmp == null) {
callbackContext.error("The image could not be decoded");
if (imageFile == null) {
callbackContext.error("Error while saving image");
}
} else {
// Update image gallery
if (mediaScannerEnabled) {
scanPhoto(imageFile);
}
// Save the image
File imageFile = savePhoto(bmp, filePrefix);
callbackContext.success(imageFile.toString());
}
if (imageFile == null) {
callbackContext.error("Error while saving image");
}
return true;
}
// Update image gallery
scanPhoto(imageFile);
private File savePhoto(Bitmap bmp, String prefix) {
File retVal = null;
callbackContext.success(imageFile.toString());
}
try {
String deviceVersion = Build.VERSION.RELEASE;
Calendar c = Calendar.getInstance();
String date = EMPTY_STR
+ c.get(Calendar.YEAR)
+ c.get(Calendar.MONTH)
+ c.get(Calendar.DAY_OF_MONTH)
+ c.get(Calendar.HOUR_OF_DAY)
+ c.get(Calendar.MINUTE)
+ c.get(Calendar.SECOND);
return true;
int check = deviceVersion.compareTo("2.3.3");
} else {
File folder;
return false;
}
}
/*
* File path = Environment.getExternalStoragePublicDirectory(
* Environment.DIRECTORY_PICTURES ); //this throws error in Android
* 2.2
*/
if (check >= 1) {
folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
private File savePhoto(Bitmap bmp, String prefix) {
File retVal = null;
if (!folder.exists()) {
folder.mkdirs();
}
try {
String deviceVersion = Build.VERSION.RELEASE;
Calendar c = Calendar.getInstance();
String date = EMPTY_STR
+ c.get(Calendar.YEAR)
+ c.get(Calendar.MONTH)
+ c.get(Calendar.DAY_OF_MONTH)
+ c.get(Calendar.HOUR_OF_DAY)
+ c.get(Calendar.MINUTE)
+ c.get(Calendar.SECOND);
} else {
folder = Environment.getExternalStorageDirectory();
}
File imageFile = new File(folder, prefix + date + ".png");
Log.i("Base64ToGallery", "Android version " + deviceVersion);
FileOutputStream out = new FileOutputStream(imageFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
int check = deviceVersion.compareTo("2.3.3");
retVal = imageFile;
File folder;
} catch (Exception e) {
Log.e("Base64ToGallery", "An exception occured while saving image: " + e.toString());
}
/*
* File path = Environment.getExternalStoragePublicDirectory(
* Environment.DIRECTORY_PICTURES ); //this throws error in Android
* 2.2
*/
if (check >= 1) {
folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return retVal;
}
if (!folder.exists()) {
folder.mkdirs();
}
} else {
folder = Environment.getExternalStorageDirectory();
}
File imageFile = new File(folder, prefix + date + ".png");
FileOutputStream out = new FileOutputStream(imageFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
retVal = imageFile;
} catch (Exception e) {
Log.e("Base64ToGallery", "An exception occured while saving image: " + e.toString());
}
return retVal;
}
/**
* Invoke the system's media scanner to add your photo to the Media Provider's database,
* making it available in the Android Gallery application and to other apps.
*/
private void scanPhoto(File imageFile) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
/**
* Invoke the system's media scanner to add your photo to the Media Provider's database,
* making it available in the Android Gallery application and to other apps.
*/
private void scanPhoto(File imageFile) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(imageFile);
mediaScanIntent.setData(contentUri);
cordova.getActivity().sendBroadcast(mediaScanIntent);
}
cordova.getActivity().sendBroadcast(mediaScanIntent);
}
}

View File

@@ -2,21 +2,20 @@
// Base64ToGallery.h
// Base64ToGallery PhoneGap/Cordova plugin
//
// Created by Tommy-Carlos Williams on 29/03/12.
// Copyright (c) 2012 Tommy-Carlos Williams. All rights reserved.
// Copyright (c) 2016 StefanoMagrassi <stefano.magrassi@gmail.com>
//
// Based on Tommy-Carlos Williams "Canvas2ImagePlugin.h"
//
// MIT Licensed
//
#import <Cordova/CDVPlugin.h>
#import <Cordova/CDV.h>
@interface Base64ToGallery : CDVPlugin
{
NSString* callbackId;
}
@property (nonatomic, copy) NSString* callbackId;
@property (nonatomic, copy) NSString* callbackId;
@property (nonatomic, assign) CDVPluginResult* result;
- (void)saveImageDataToLibrary:(CDVInvokedUrlCommand*)command;
- (void)saveImageDataToLibrary:(CDVInvokedUrlCommand*)command;
@end

View File

@@ -2,8 +2,10 @@
// Base64ToGallery.m
// Base64ToGallery PhoneGap/Cordova plugin
//
// Created by Tommy-Carlos Williams on 29/03/12.
// Copyright (c) 2012 Tommy-Carlos Williams. All rights reserved.
// Copyright (c) 2016 StefanoMagrassi <stefano.magrassi@gmail.com>
//
// Based on Tommy-Carlos Williams "Canvas2ImagePlugin.m"
//
// MIT Licensed
//
@@ -11,48 +13,46 @@
#import <Cordova/CDV.h>
@implementation Base64ToGallery
@synthesize callbackId;
//-(CDVPlugin*) initWithWebView:(UIWebView*)theWebView
//{
// self = (Base64ToGallery*)[super initWithWebView:theWebView];
// return self;
//}
- (void)saveImageDataToLibrary:(CDVInvokedUrlCommand*)command
{
self.callbackId = command.callbackId;
NSData* imageData = [NSData dataFromBase64String:[command.arguments objectAtIndex:0]];
UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
// Was there an error?
if (error != NULL)
- (void)saveImageDataToLibrary:(CDVInvokedUrlCommand*)command
{
// Show error message...
NSLog(@"ERROR: %@",error);
CDVPluginResult* result = [CDVPluginResult resultWithStatus: CDVCommandStatus_ERROR messageAsString:error.description];
[self.webView stringByEvaluatingJavaScriptFromString:[result toErrorCallbackString: self.callbackId]];
[self.commandDelegate runInBackground:^{
self.callbackId = command.callbackId;
self.result = nil;
NSString* base64String = [command.arguments objectAtIndex:0];
if (base64String != nil && [base64String length] > 0) {
NSData* imageData = [[[NSData alloc] initWithBase64EncodedString:base64String options:0] autorelease];
UIImage* image = [[[UIImage alloc] initWithData:imageData] autorelease];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
} else {
self.result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
[self.commandDelegate sendPluginResult:self.result callbackId:self.callbackId];
}
}];
}
else // No errors
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
// Show message image successfully saved
NSLog(@"IMAGE SAVED!");
CDVPluginResult* result = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsString:@"Image saved"];
[self.webView stringByEvaluatingJavaScriptFromString:[result toSuccessCallbackString: self.callbackId]];
// With errors
if (error != NULL) {
NSLog(@"ERROR: %@", error);
self.result = [CDVPluginResult resultWithStatus: CDVCommandStatus_ERROR messageAsString:error.description];
// No errors
} else {
self.result = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK];
}
[self.commandDelegate sendPluginResult:self.result callbackId:self.callbackId];
}
}
- (void)dealloc
{
[callbackId release];
[super dealloc];
}
@end

View File

@@ -22,11 +22,6 @@ public class Base64ToGallery : BaseCommand
string prefix = options[1];
byte[] imageBytes = Convert.FromBase64String(imageData);
if (String.IsNullOrEmpty(prefix))
{
prefix = "img_";
}
using (var imageStream = new MemoryStream(imageBytes))
{
imageStream.Seek(0, SeekOrigin.Begin);
@@ -37,7 +32,7 @@ public class Base64ToGallery : BaseCommand
if (picture.Name.Contains(fileName))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "Image saved: " + picture.Name));
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
else
{

View File

@@ -7,48 +7,52 @@
* @license MIT
*/
/*globals cordova*/
var exec = require('cordova/exec');
var assign = require('./object.assign-polyfill');
// Consts
// ------
var SERVICE = 'Base64ToGallery';
var ACTION = 'saveImageDataToLibrary';
var SERVICE = 'Base64ToGallery';
var ACTION = 'saveImageDataToLibrary';
var ARGS = ['data', 'prefix', 'mediaScanner'];
var DEFAULTS = { prefix: 'img_', mediaScanner: true };
/**
* @property indexFromArgs - Partially applied "indexFrom" method with ARGS constant.
* @private
*/
var indexFromArgs = indexFrom.bind(null, ARGS);
// Exports
// -------
/**
* Saves base64 data as image.
* @public
* @param {string} data
* @param {string} [prefix]
* @param {function} [success]
* @param {function} [fail]
* @return {undefined}
*/
module.exports = function(data, prefix, success, fail) {
// Handle method call with 3 or 4 parameters (prefix optional)
if (arguments.length < 4) {
prefix = '';
success = arguments[1];
fail = arguments[2];
}
module.exports = function(data, options, success, fail) {
var spec = assign(DEFAULTS, options);
var actionArgs = prepareArgs(spec);
// Prepare base64 string
data = data.replace(/data:image\/png;base64,/, '');
return cordova.exec(ok(success), error(fail), SERVICE, ACTION, [data, prefix]);
// And add it to the Service's Action arguments
actionArgs.unshift(data);
return exec(ok(success), error(fail), SERVICE, ACTION, actionArgs);
};
// Private methods
// ---------------
/**
* Gets success callback if it is defined and not null.
* Otherwise returns a simple console.log.
*
* @private
* @param {[function|undefined|null]} success
* @return {function}
*/
function ok(success) {
if (typeof success === 'undefined' || success === null) {
if (typeof success !== 'function') {
return console.log;
}
@@ -58,14 +62,53 @@ function ok(success) {
/**
* Gets fail callback if it is defined and not null.
* Otherwise returns a simple console.error.
*
* @private
* @param {[function|undefined|null]} fail
* @return {function}
*/
function error(fail) {
if (typeof fail === 'undefined' || fail === null) {
if (typeof fail !== 'function') {
return console.error;
}
return fail;
}
/**
* Gets index of item from array.
* @private
* @param {array} fromArr - Source array
* @param {*} item - Item
* @return {number} Index of item in array
*/
function indexFrom(fromArr, item) {
return fromArr.indexOf(item);
}
/**
* Gets value of property with specified key from object.
* @private
* @param {object} fromObj - Source object
* @param {string} key - Property key
* @return {*} Property value
*/
function valueFrom(fromObj, key) {
return fromObj[key];
}
/**
* Prepares parameter to pass to Service's Action.<br/>
* Sort options value in order to match "arguments" proto.
* @private
* @param {object} opts - Options object
* @return {array} Arguments array
*/
function prepareArgs(opts) {
var valueFromOpts = valueFrom.bind(null, opts);
return Object.keys(opts).reduce(function(acc, item) {
acc.splice(indexFromArgs(item), 0, valueFromOpts(item));
return acc;
}, []);
}

View File

@@ -0,0 +1,34 @@
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
module.exports = Object.assign;