summaryrefslogtreecommitdiff
path: root/plugins/org.devgeeks.Canvas2ImagePlugin
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/org.devgeeks.Canvas2ImagePlugin')
-rw-r--r--plugins/org.devgeeks.Canvas2ImagePlugin/README.md53
-rw-r--r--plugins/org.devgeeks.Canvas2ImagePlugin/plugin.xml70
-rw-r--r--plugins/org.devgeeks.Canvas2ImagePlugin/src/android/Canvas2ImagePlugin.java126
-rw-r--r--plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.h22
-rw-r--r--plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.m58
-rw-r--r--plugins/org.devgeeks.Canvas2ImagePlugin/src/wp8/Canvas2ImagePlugin.cs49
-rw-r--r--plugins/org.devgeeks.Canvas2ImagePlugin/www/Canvas2ImagePlugin.js27
7 files changed, 405 insertions, 0 deletions
diff --git a/plugins/org.devgeeks.Canvas2ImagePlugin/README.md b/plugins/org.devgeeks.Canvas2ImagePlugin/README.md
new file mode 100644
index 00000000..022f8ab1
--- /dev/null
+++ b/plugins/org.devgeeks.Canvas2ImagePlugin/README.md
@@ -0,0 +1,53 @@
+Canvas2ImagePlugin
+============
+
+This plugin allows you to save the contents of an HTML canvas tag to the iOS Photo Library, Android Gallery or WindowsPhone 8 Photo Album from your app.
+
+See an example project using it here: [https://github.com/devgeeks/Canvas2ImageDemo](https://github.com/devgeeks/Canvas2ImageDemo) - note: this app does not work in wp8.
+
+Installation
+------------
+
+### For Cordova 3.0.x:
+
+1. To add this plugin just type: `cordova plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git` or `phonegap local plugin add https://github.com/devgeeks/Canvas2ImagePlugin.git`
+2. To remove this plugin type: `cordova plugin remove org.devgeeks.Canvas2ImagePlugin` or `phonegap local plugin remove org.devgeeks.Canvas2ImagePlugin`
+
+### NOTE: For older versions of Cordova (You will probably have to use tag 0.2.0)
+
+Usage:
+------
+
+Call the `window.canvas2ImagePlugin.saveImageDataToLibrary()` method using success and error callbacks and the id attribute or the element object of the canvas to save:
+
+### Example
+```html
+<canvas id="myCanvas" width="165px" height="145px"></canvas>
+```
+
+```javascript
+function onDeviceReady()
+{
+ window.canvas2ImagePlugin.saveImageDataToLibrary(
+ function(msg){
+ console.log(msg);
+ },
+ function(err){
+ console.log(err);
+ },
+ document.getElementById('myCanvas')
+ );
+}
+```
+
+## License
+
+The MIT License
+
+Copyright (c) 2011 Tommy-Carlos Williams (http://github.com/devgeeks)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/plugins/org.devgeeks.Canvas2ImagePlugin/plugin.xml b/plugins/org.devgeeks.Canvas2ImagePlugin/plugin.xml
new file mode 100644
index 00000000..657a04dc
--- /dev/null
+++ b/plugins/org.devgeeks.Canvas2ImagePlugin/plugin.xml
@@ -0,0 +1,70 @@
+<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ id="org.devgeeks.Canvas2ImagePlugin"
+ version="0.6.0">
+
+ <name>Canvas 2 Image</name>
+
+ <engines>
+ <engine name="cordova" version=">=3.0.0" />
+ </engines>
+
+ <description>This plugin allows you to save the contents of an HTML canvas tag to the iOS Photo Library, or Android Gallery from your app.</description>
+ <author>Tommy-Carlos Williams - tommy@devgeeks.org</author>
+ <keywords>canvas,image,photo library</keywords>
+
+ <license>MIT</license>
+
+ <js-module src="www/Canvas2ImagePlugin.js" name="Canvas2ImagePlugin">
+ <clobbers target="window.canvas2ImagePlugin" />
+ </js-module>
+
+ <!-- ios -->
+ <platform name="ios">
+ <config-file target="config.xml" parent="/*">
+ <feature name="Canvas2ImagePlugin">
+ <param name="ios-package" value="Canvas2ImagePlugin"/>
+ <param name="onload" value="true" />
+ </feature>
+ </config-file>
+
+ <header-file src="src/ios/Canvas2ImagePlugin.h" />
+
+ <source-file src="src/ios/Canvas2ImagePlugin.m"
+ compiler-flags="-fno-objc-arc" />
+ </platform>
+
+ <!-- android -->
+ <platform name="android">
+
+ <config-file target="AndroidManifest.xml" parent="/*">
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ </config-file>
+
+ <config-file target="res/xml/config.xml" parent="/*">
+ <feature name="Canvas2ImagePlugin" >
+ <param name="android-package" value="org.devgeeks.Canvas2ImagePlugin.Canvas2ImagePlugin"/>
+ </feature>
+ </config-file>
+
+ <source-file src="src/android/Canvas2ImagePlugin.java"
+ target-dir="src/org/devgeeks/Canvas2ImagePlugin" />
+
+ </platform>
+
+ <!-- wp8 -->
+ <platform name="wp8">
+ <config-file target="config.xml" parent="/*">
+ <feature name="Canvas2ImagePlugin">
+ <param name="wp-package" value="Canvas2ImagePlugin"/>
+ <param name="onload" value="true" />
+ </feature>
+ </config-file>
+
+ <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities">
+ <Capability Name="ID_CAP_MEDIALIB_PHOTO" />
+ </config-file>
+
+ <source-file src="src/wp8/Canvas2ImagePlugin.cs" />
+ </platform>
+</plugin>
diff --git a/plugins/org.devgeeks.Canvas2ImagePlugin/src/android/Canvas2ImagePlugin.java b/plugins/org.devgeeks.Canvas2ImagePlugin/src/android/Canvas2ImagePlugin.java
new file mode 100644
index 00000000..90118c0b
--- /dev/null
+++ b/plugins/org.devgeeks.Canvas2ImagePlugin/src/android/Canvas2ImagePlugin.java
@@ -0,0 +1,126 @@
+package org.devgeeks.Canvas2ImagePlugin;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.Calendar;
+
+import org.apache.cordova.CallbackContext;
+import org.apache.cordova.CordovaPlugin;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.os.Build;
+import android.os.Environment;
+import android.util.Base64;
+import android.util.Log;
+
+/**
+ * Canvas2ImagePlugin.java
+ *
+ * Android implementation of the Canvas2ImagePlugin for iOS.
+ * Inspirated by Joseph's "Save HTML5 Canvas Image to Gallery" plugin
+ * http://jbkflex.wordpress.com/2013/06/19/save-html5-canvas-image-to-gallery-phonegap-android-plugin/
+ *
+ * @author Vegard Løkken <vegard@headspin.no>
+ */
+public class Canvas2ImagePlugin extends CordovaPlugin {
+ public static final String ACTION = "saveImageDataToLibrary";
+
+ @Override
+ public boolean execute(String action, JSONArray data,
+ CallbackContext callbackContext) throws JSONException {
+
+ if (action.equals(ACTION)) {
+
+ String base64 = data.optString(0);
+ if (base64.equals("")) // isEmpty() requires API level 9
+ callbackContext.error("Missing base64 string");
+
+ // Create the bitmap from the base64 string
+ Log.d("Canvas2ImagePlugin", base64);
+ byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
+ Bitmap bmp = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
+ if (bmp == null) {
+ callbackContext.error("The image could not be decoded");
+ } else {
+
+ // Save the image
+ File imageFile = savePhoto(bmp);
+ if (imageFile == null)
+ callbackContext.error("Error while saving image");
+
+ // Update image gallery
+ scanPhoto(imageFile);
+
+ callbackContext.success(imageFile.toString());
+ }
+
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private File savePhoto(Bitmap bmp) {
+ File retVal = null;
+
+ try {
+ Calendar c = Calendar.getInstance();
+ String date = "" + c.get(Calendar.DAY_OF_MONTH)
+ + c.get(Calendar.MONTH)
+ + c.get(Calendar.YEAR)
+ + c.get(Calendar.HOUR_OF_DAY)
+ + c.get(Calendar.MINUTE)
+ + c.get(Calendar.SECOND);
+
+ String deviceVersion = Build.VERSION.RELEASE;
+ Log.i("Canvas2ImagePlugin", "Android version " + deviceVersion);
+ int check = deviceVersion.compareTo("2.3.3");
+
+ File folder;
+ /*
+ * File path = Environment.getExternalStoragePublicDirectory(
+ * Environment.DIRECTORY_PICTURES ); //this throws error in Android
+ * 2.2
+ */
+ if (check >= 1) {
+ folder = Environment
+ .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
+
+ if(!folder.exists()) {
+ folder.mkdirs();
+ }
+ } else {
+ folder = Environment.getExternalStorageDirectory();
+ }
+
+ File imageFile = new File(folder, "c2i_" + date.toString() + ".png");
+
+ FileOutputStream out = new FileOutputStream(imageFile);
+ bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
+ out.flush();
+ out.close();
+
+ retVal = imageFile;
+ } catch (Exception e) {
+ Log.e("Canvas2ImagePlugin", "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);
+ Uri contentUri = Uri.fromFile(imageFile);
+ mediaScanIntent.setData(contentUri);
+ cordova.getActivity().sendBroadcast(mediaScanIntent);
+ }
+}
diff --git a/plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.h b/plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.h
new file mode 100644
index 00000000..ef7bc567
--- /dev/null
+++ b/plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.h
@@ -0,0 +1,22 @@
+//
+// Canvas2ImagePlugin.h
+// Canvas2ImagePlugin PhoneGap/Cordova plugin
+//
+// Created by Tommy-Carlos Williams on 29/03/12.
+// Copyright (c) 2012 Tommy-Carlos Williams. All rights reserved.
+// MIT Licensed
+//
+
+
+#import <Cordova/CDVPlugin.h>
+
+@interface Canvas2ImagePlugin : CDVPlugin
+{
+ NSString* callbackId;
+}
+
+@property (nonatomic, copy) NSString* callbackId;
+
+- (void)saveImageDataToLibrary:(CDVInvokedUrlCommand*)command;
+
+@end
diff --git a/plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.m b/plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.m
new file mode 100644
index 00000000..734ee006
--- /dev/null
+++ b/plugins/org.devgeeks.Canvas2ImagePlugin/src/ios/Canvas2ImagePlugin.m
@@ -0,0 +1,58 @@
+//
+// Canvas2ImagePlugin.m
+// Canvas2ImagePlugin PhoneGap/Cordova plugin
+//
+// Created by Tommy-Carlos Williams on 29/03/12.
+// Copyright (c) 2012 Tommy-Carlos Williams. All rights reserved.
+// MIT Licensed
+//
+
+#import "Canvas2ImagePlugin.h"
+#import <Cordova/CDV.h>
+
+@implementation Canvas2ImagePlugin
+@synthesize callbackId;
+
+//-(CDVPlugin*) initWithWebView:(UIWebView*)theWebView
+//{
+// self = (Canvas2ImagePlugin*)[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)
+ {
+ // Show error message...
+ NSLog(@"ERROR: %@",error);
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus: CDVCommandStatus_ERROR messageAsString:error.description];
+ [self.webView stringByEvaluatingJavaScriptFromString:[result toErrorCallbackString: self.callbackId]];
+ }
+ else // No errors
+ {
+ // Show message image successfully saved
+ NSLog(@"IMAGE SAVED!");
+ CDVPluginResult* result = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsString:@"Image saved"];
+ [self.webView stringByEvaluatingJavaScriptFromString:[result toSuccessCallbackString: self.callbackId]];
+ }
+}
+
+- (void)dealloc
+{
+ [callbackId release];
+ [super dealloc];
+}
+
+
+@end
diff --git a/plugins/org.devgeeks.Canvas2ImagePlugin/src/wp8/Canvas2ImagePlugin.cs b/plugins/org.devgeeks.Canvas2ImagePlugin/src/wp8/Canvas2ImagePlugin.cs
new file mode 100644
index 00000000..6376348c
--- /dev/null
+++ b/plugins/org.devgeeks.Canvas2ImagePlugin/src/wp8/Canvas2ImagePlugin.cs
@@ -0,0 +1,49 @@
+using Microsoft.Xna.Framework.Media;
+using System;
+using System.IO;
+using System.Text;
+using WPCordovaClassLib.Cordova;
+using WPCordovaClassLib.Cordova.Commands;
+using WPCordovaClassLib.Cordova.JSON;
+
+public class Canvas2ImagePlugin : BaseCommand
+{
+ public Canvas2ImagePlugin()
+ {
+ }
+
+ public void saveImageDataToLibrary(string jsonArgs)
+ {
+ try
+ {
+ var options = JsonHelper.Deserialize<string[]>(jsonArgs);
+
+ string imageData = options[0];
+ byte[] imageBytes = Convert.FromBase64String(imageData);
+
+ using (var imageStream = new MemoryStream(imageBytes))
+ {
+ imageStream.Seek(0, SeekOrigin.Begin);
+
+ string fileName = String.Format("c2i_{0:yyyyMMdd_HHmmss}", DateTime.Now);
+ var library = new MediaLibrary();
+ var picture = library.SavePicture(fileName, imageStream);
+
+ if (picture.Name.Contains(fileName))
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.OK,
+ "Image saved: " + picture.Name));
+ }
+ else
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
+ "Failed to save image: " + picture.Name));
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ex.Message));
+ }
+ }
+}
diff --git a/plugins/org.devgeeks.Canvas2ImagePlugin/www/Canvas2ImagePlugin.js b/plugins/org.devgeeks.Canvas2ImagePlugin/www/Canvas2ImagePlugin.js
new file mode 100644
index 00000000..a5ee9fcf
--- /dev/null
+++ b/plugins/org.devgeeks.Canvas2ImagePlugin/www/Canvas2ImagePlugin.js
@@ -0,0 +1,27 @@
+//
+// Canvas2ImagePlugin.js
+// Canvas2ImagePlugin PhoneGap/Cordova plugin
+//
+// Created by Tommy-Carlos Williams on 29/03/12.
+// Copyright (c) 2012 Tommy-Carlos Williams. All rights reserved.
+// MIT Licensed
+//
+
+ module.exports = {
+
+ saveImageDataToLibrary:function(successCallback, failureCallback, canvasId) {
+ // successCallback required
+ if (typeof successCallback != "function") {
+ console.log("Canvas2ImagePlugin Error: successCallback is not a function");
+ }
+ else if (typeof failureCallback != "function") {
+ console.log("Canvas2ImagePlugin Error: failureCallback is not a function");
+ }
+ else {
+ var canvas = (typeof canvasId === "string") ? document.getElementById(canvasId) : canvasId;
+ var imageData = canvas.toDataURL().replace(/data:image\/png;base64,/,'');
+ return cordova.exec(successCallback, failureCallback, "Canvas2ImagePlugin","saveImageDataToLibrary",[imageData]);
+ }
+ }
+ };
+