Save canvas image on local mobile storage for IOS/Android - javascript

Im using the fabric javascript library to create a custom image. All the data is saved in a canvas and is shown using canvas tag. After displaying the image, I would like to give the user the option to save it locally. Anyone has any idea how to do that? The solution should work for IOs and Android, I've tried several alternatives but still no luck.
[Update 1]
I tried using the Canvas2ImagePlugin but for some reason my app restarts when running the window.canvas2ImagePlugin.saveImageDataToLibrary command.
My code (I want to save the image when the users touches the saveButton):
$(document).on('click', '#saveButton', function(e){
window.canvas2ImagePlugin.saveImageDataToLibrary(
function(msg){
console.log(msg);
},
function(err){
console.log(err);
},
document.getElementById('c')
);
});
This is shown in the browser logs after the app restarts:
deviceready has not fired after 5 seconds. (13:09:28:529)
at file:///android_asset/www/cordova.js:1169
Channel not fired: onPluginsReady (13:09:28:542)
at file:///android_asset/www/cordova.js:1162
Channel not fired: onCordovaReady (13:09:28:550)
at file:///android_asset/www/cordova.js:1162
Channel not fired: onDOMContentLoaded (13:09:28:557)
at file:///android_asset/www/cordova.js:1162
I also noticed that when Netbeans builds my app, for some reason it deletes the plugin. This is part of the build output:
update-plugins:
cordova.cmd plugins
cordova.cmd -d plugin remove org.devgeeks.Canvas2ImagePlugin
Calling plugman.uninstall on plugin "org.devgeeks.Canvas2ImagePlugin" for platform "android"
Uninstalling org.devgeeks.Canvas2ImagePlugin from android
[Update 2]
After some research I found out that I had to add the plugin manually in the file \nbproject\plugin.properties. Now its working perfectly. Thank you AtanuCSE

try this plugin
Canvas2ImagePlugin
<canvas id="myCanvas" width="165px" height="145px"></canvas>
function onDeviceReady()
{
window.canvas2ImagePlugin.saveImageDataToLibrary(
function(msg){
console.log(msg);
},
function(err){
console.log(err);
},
document.getElementById('myCanvas')
);
}

With Canvas2ImagePlugin now u can choose either to save as jpg/png, set quality and set outputfolder
function onDeviceReady()
{
window.canvas2ImagePlugin.saveImageDataToLibrary(
function(msg){
console.log(msg); //msg is the filename path (for android and iOS)
},
function(err){
console.log(err);
},
document.getElementById('myCanvas'),
'.jpg', // save as jpg
80, // image quality
'cunvaspluginfolder' //folder name
);
}
Credit to wbt11a because make this plugin more configurable from original author.
Please download the new plugin here Github source

Related

cant use webcam in phone but in pc it works fine

I'm trying to put a QR barcode scanner in my website using Quagga after lots of trying I finally succeeded to put the live reader, its ask for permission to use in the pc but when I'm trying to access it through my phone it doesn't work, and by doesn't work I mean doesn't even ask for permission to open the camera
I am rendering the script tag on the ejs file and it looks something like this:
<script src="js/quagga.min.js"></script>
<script>
Quagga.init({
inputStream : {
name : "Live",
type : "LiveStream",
target: document.querySelector('#camera')
},
decoder : {
readers : ["code_128_reader"]
}
}, function(err) {
if (err) {
console.log(err);
return
}
console.log("Initialization finished. Ready to start");
Quagga.start();
});
Quagga.onDetected(function(data){
document.body.appendChild("<h1>"+data.codeResult.code +"</h1>")
});
</script>
Thanks in advance!
SOLVED!
for the chrome version that is 47+, it seems like you don't have permission to use the camera on unsecure website, and mine was on the localhost.
so I got into the chrome flags and inside of that I searched "Insecure origin treated as secure" and then I added my laptop IP and the opened port and it worked!
the "Yahha Udin" question answered by "Kartik Sharma" (link below) helped me solve it.
link: "unsafely-treat-insecure-origin-as-secure" flag is not working on Chrome

Cordova camera saves to gallery even on false

I'm in a really nasty situation...
My client wants a Cordova application in Ionic Framework v1, and it's imperative that the camera does not save images to gallery. However, when I set the parameter for saving to gallery to false, it is still saving to gallery.
The problem occurs on Android when you take a photo and cancel it. It then saves that picture to gallery and sometimes even saves all other pictures after that.
I would really welcome any kind of help; All I've found so far are some solutions that I find really hard to understand since my knowledge of Java is zero.
Here is my JS code
function capturePhoto() {
var maxDimension = 1280;
var options = {
quality: 80,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
correctOrientation: true,
targetWidth: maxDimension,
targetHeight: maxDimension,
saveToPhotoAlbum: false
};
This is for camera options.
$cordovaCamera.getPicture(options).then(function (imageData) {
var src = "data:image/jpeg;base64," + imageData;
$scope.photoPreviewSrc = src;
}).catch(function (err) {
});
}
I have checked with your code using cordova. It works fine as expected.
Verify your app in other device once.
I haven't checked it on ionic platform.
You may want to try running something like the following after you receive the image data:
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}
From the docs: "camera.cleanup() Removes intermediate image files that are kept in temporary storage after calling camera.getPicture. Applies only when the value of Camera.sourceType equals Camera.PictureSourceType.CAMERA and the Camera.destinationType equals Camera.DestinationType.FILE_URI."
The above relates directly to your use case.
Is it really going to the photo gallery, or just showing up in Android's photo app? The Android default photo browser will show all photos, screenshots, etc. It will also even show just random images - that other Apps may have on the file system, but that aren't photos.
Since in cordova, you don't have great control of the OS, you can use a work around: You can place the images in a hidden directory (starting with a . such .appdata) and this will prevent Android from automatically seeing the images from the "Gallery" app. I had this problem in an Ionic App and solved it that way.

Cordova record audio on ios9 does not work

I am using Cordova to build an html5/JS app.
I have to record and play audio, so i use Media & File plug-ins, but i have problem to make it work on iOS.
My steps :
1)
I detect platform (Android or iOS).
If Android, no need to set anything, it works.
If Ios, I set the file URI to '../Library/NoCloud/' (after reading Raymond Camden article),
then I create file before recording :
var mediaBaseUrl = '';
if(app.isIOS){
mediaBaseUrl ='../Library/NoCloud/';
createFileSystem();
}
My createFile function is :
createFileSystem : function(){
var fileName= mediaBaseUrl+[myFileName];
//asking for a new space
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
//success
function(fileSystem){
fileSystem.root.getFile(
fileName,
{ create: true, exclusive: false },
//success callback
function(){
console.log('ok file created');
},
null
);
},
// error
function() {
console.log("***log: failed in creating media file in requestFileSystem");
}
);
},
2) Once file is created, i create recorded file with Media constructor :
var recordedFile = new Media(
mediaBaseUrl + [myFileName],
// success callback
function () {},
// error callback
function (err) {
console.log("recorded file error " );
console.log(err)
}
);
3) In config XML, i have this line to record in iOS Library Folder, and no save in Cloud :
<preference name="iosPersistentFileLocation" value="Library" />
<preference name="BackupWebStorage" value="none" />
My problem :
On Android device, all is fine, i can record then listen audio file.
But on iOS device (ipad2), some things are strange :
with my filename "../Library/NoCloud/myFileName", i have no success callback for fileSystem.root.getFile function, but i can see a file with the good name and the good place in my ipad Library/NoCloud folder, except the file is empty. So the Media constructor can not play the file and return an error.
if i set myFileName as "myFileName", i have the callback of file creation ('ok file created'), but the Media constructor cannot access to the file and return the error :
message: "Cannot use audio file from resource 'test.wav'", code: 1
I have checked ipad microphone, it is activated for this app. I believe it worked before the iOS update on ipad (now iOS 9.3.2), btu i am not sure anymore.
Is there something that i did wrong, or is there a new way to process ?
thanks !
You have to include cdvfile://localhost/library-nosync/ with /Library/NoCloud
that is cdvfile://localhost/library-nosync//Library/NoCloud has to be given in the url sorce
Remember the url is given assuming library folder is inside www folder and it follows
This issue is being there from ios9 and after

VS2015 Cordova Sms Plugin Sms.Send doesn't work in Index.JS (ondeviceReady)

I'm new to Cordova, any help would be appreciated.
I created a new Cordova Project in VS2015 and added the Cordova SMS plugin to my project (https://www.npmjs.com/package/cordova-sms-plugin).
I added this code to /www/scripts/index.js function onDeviceReady (as per documentiation for plugin):
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
var numberString = "aoeuaeu";
var bypassAppChooser = true;
//CONFIGURATION
var options = {
replaceLineBreaks: false,
android: {
intent: 'INTENT' // send SMS with the native android SMS messaging
}
};
var successSMS = function () { alert('Message sent successfully'); };
var errorSMS = function (e) { alert('Message Failed:' + e); };
sms.send("0811231234", "Testing123", options, successSMS, errorSMS);
I debug the project using Debug, Android, Ripple - Nexus (Galaxy) selected options. When I place a breakpoint on the sms.send line of code and I add a watch for 'sms.send', I can see the object exists.
When I single step, this line in sms.js seems to be the last line that executes:
// fire
exec(
success,
failure,
'Sms',
'send', [phone, message, androidIntent, replaceLineBreaks]
);
I then get the following error message in Ripple:
'Sms.send We seem to be missing some stuff :( What is kinda cool though you can fill in the textarea to pass a json object to the callback you want to execute).'
I can see that all of the objects in that line is defined (success, failure, phone, message, androidIntent, replaceLineBreaks). When I 'step into' this line, it continues to execute code in ripple.js, but it becomes hard to follow for a person, since there are no line breaks in this file.
What am I doing wrong? I've read through all the documentation I can find & searched stackoverflow questions and can't seem to find any solutions to the problem.
I've uploaded this entire project (zipped), which can be downloaded at:
https://drive.google.com/file/d/0BwWgTMh-JLbfNHV0MlE5Yk5IZ3M/view?usp=sharing
Thanks in advance
Thank you Cordova team at Microsoft for helping me with an answer:
"Ripple has the ability to emulate some but not all plugins. SMS is not one of the plugins that it can fully emulate. However, in the message that pops up, you do have the ability to hit the Success or Fail buttons which will report back to the app that it was successful or not in sending the SMS. While that doesn’t actually send a message, it does let you test your app to see how it behaves for different results.
I tried the bit of sample code you included in the first email. In Ripple, I was able to change the alert by hitting the different buttons.
Trying other deployment methods, in both the VS Android Emulator and the Google Emulator they showed failure alert messages that they don’t support SMS messages. I then launched it on an Android phone device and it said it was successful.
So I believe your options are mainly using Ripple to fake sending of messages or using a device for testing."

How to implement in-app-purchase using Cordova plugin?

Please tell me the way to implement in-app-purchase using Cordova plugin.
I'm developing Android application using Cordova.
There are some in-app-purchase plugins but I decide to use Cordova Purchase Plugin.
I did some setups along README.md of In-App Purchase for PhoneGap / Cordova iOS and Android.
As a result, I could call the Plugin using Demo of the Purchase Plugin for Cordova with my little modification. (See the following, it is a portion of code.)
app.initStore = function() {
if (!window.store) {
log('Store not available');
return;
}
// Enable maximum logging level
store.verbosity = store.DEBUG;
// Enable remote receipt validation
// store.validator = "https://api.fovea.cc:1982/check-purchase";
// Inform the store of your products
log('registerProducts');
store.register({
id: 'myProductA',
alias: 'myProductA',
type: store.CONSUMABLE
});
// When any product gets updated, refresh the HTML.
store.when("product").updated(function (p) {
console.info("app.renderIAP is called");
app.renderIAP(p);
});
// Log all errors
store.error(function(error) {
log('ERROR ' + error.code + ': ' + error.message);
});
// When purchase of an extra life is approved,
// deliver it... by displaying logs in the console.
store.when("myProductA").approved(function (order) {
log("You got a ProductA");
order.finish();
});
// When the store is ready (i.e. all products are loaded and in their "final"
// state), we hide the "loading" indicator.
//
// Note that the "ready" function will be called immediately if the store
// is already ready.
store.ready(function() {
var el = document.getElementById("loading-indicator");
console.info(el + "ready is called")
if (el)
el.style.display = 'none';
});
// When store is ready, activate the "refresh" button;
store.ready(function() {
var el = document.getElementById('refresh-button');
console.info(el + "ready is called and refresh-button show?");
if (el) {
el.style.display = 'block';
el.onclick = function(ev) {
store.refresh();
};
}
});
// Refresh the store.
//
// This will contact the server to check all registered products
// validity and ownership status.
//
// It's fine to do this only at application startup, as it could be
// pretty expensive.
log('refresh');
store.refresh();
};
It did not show 'Store not available' that is shown when plugin is not available, show 'registerProducts', and 'refresh.'
(*Of course I added 'myProductA' to in-app Products on Google Play Developer Console.)
But I noticed that the below function is not called.
store.when("product").updated(function (p)
And also I couldn't understand what the parameter should fill in it, so I commented out the below.
(*I did remove the comment out, but it still not working.)
store.validator = "https://api.fovea.cc:1982/check-purchase";
I guess those things make something wrong.
I'm not sure what is stack on me, so my question is not clearly.
I want some clues to solve it... or I shouldn't implement in-app-purchase using Cordova plugin?
Please give me your hand.
(I'm not fluent in English, so I'm sorry for any confusion.)
You can try this plugin as an alternative: https://github.com/AlexDisler/cordova-plugin-inapppurchase
Here's an example of loading products and making a purchase:
inAppPurchase
.buy('com.yourapp.consumable_prod1')
.then(function (data) {
// ...then mark it as consumed:
return inAppPurchase.consume(data.productType, data.receipt, data.signature);
})
.then(function () {
console.log('product was successfully consumed!');
})
.catch(function (err) {
console.log(err);
});
It supports both Android and iOS.
Step for Integrate In-App billing in Phone-gap app.
1>> clone this project in your pc from this link In-App billing Library
2>> using CMD go to your root directory of your phonegap application
3>> then run this command cordova plugin add /path/to/your/cloned project --variable BILLING_KEY="QWINMERR..........RIGR"
Notes : for BILLING_KEY go to Developer console then open your application and go to Service& APIs for more info Please refer attached screenshots

Categories

Resources