Cordova camera saves to gallery even on false - javascript

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.

Related

Take desktop screenshot with Electron

I am using Electron to create a Windows application that creates a fullscreen transparent overlay window. The purpose of this overlay is to:
take a screenshot of the entire screen (not the overlay itself which is transparent, but the screen 'underneath'),
process this image by sending the image as a byte stream to my python server, and
draw some things on the overlay
I am getting stuck on the first step, which is the screenshot capturing process.
I tried option 1, which is to use capturePage():
this.electronService.remote.getCurrentWindow().webContents.capturePage()
.then((img: Electron.NativeImage) => { ... }
but this captures my overlay window only (and not the desktop screen). This will be a blank image which is useless to me.
Option 2 is to use desktopCapturer:
this.electronService.remote.desktopCapturer.getSources({types: ['screen']}).then(sources => {
for (const source of sources) {
if (source.name === 'Screen 1') {
try {
const mediaDevices = navigator.mediaDevices as any;
mediaDevices.getUserMedia({
audio: false,
video: { // this specification is only available for Chrome -> Electron runs on Chromium browser
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: source.id,
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}).then((stream: MediaStream) => { // stream.getVideoTracks()[0] contains the video track I need
this.handleStream(stream);
});
} catch (e) {
}
}
}
});
The next step is where it becomes fuzzy for me. What do I do with the acquired MediaStream to get a bytestream from the screenshot out of it? I see plenty of examples how to display this stream on a webpage, but I wish to send it to my backend. This StackOverflow post mentions how to do it, but I am not getting it to work properly. This is how I implemented handleStream():
import * as MediaStreamRecorder from 'msr';
private handleStream(stream: MediaStream): void {
recorder.stop()
const recorder = new MediaStreamRecorder(stream);
recorder.ondataavailable = (blob: Blob) => { // I immediately get a blob, while the linked SO page got an event and had to get a blob through event.data
this.http.post<Result>('http://localhost:5050', blob);
};
// make data available event fire every one second
recorder.start(1000);
}
The blob is not being accepted by the Python server. Upon inspecting the contents of Blob, it's a video as I suspected. I verified this with the following code:
let url = URL.createObjectURL(blob);
window.open(url, '_blank')
which opens the blob in a new window. It displays a video of maybe half a second, but I want to have a static image. So how do I get a specific snapshot out of it? I'm also not sure if simply sending the Javascript blob format in the POST body will do for Python to be correctly interpret it. In Java it works by simply sending a byte[] of the image so I verified that the Python server implementation works as expected.
Any suggestions other than using the desktopCapturer are also fine. This implementation is capturing my mouse as well, which I rather not have. I must admit that I did not expect this feature to be so difficult to implement.
Here's how you take a desktop screenshot:
const { desktopCapturer } = require('electron')
document.getElementById('screenshot-button').addEventListener('click', () => { // The button which takes the screenshot
desktopCapturer.getSources({ types: ['screen'] })
.then( sources => {
document.getElementById('screenshot-image').src = sources[0].thumbnail.toDataURL() // The image to display the screenshot
})
})
Using 'screen' will take a screenshot of the entire desktop.
Using 'windows' will take a screenshot of only the application.
Also refer to these docs: https://www.electronjs.org/docs/api/desktop-capturer
desktopCapturer only takes videos. So you need to get a single frame from it. You can use html5 canvas for that. Here is an example:
https://ourcodeworld.com/articles/read/280/creating-screenshots-of-your-app-or-the-screen-in-electron-framework
Or, use some third party screenshot library available on npm. The one I found needs to have ImageMagick installed on linux, but maybe there are more, or you don't need to support linux. You'll need to do that in the main electron process in which you can do anything that you can do in node.
You can get each frame from taken video like this:
desktopCapturer.getSources({
types: ['window'], thumbnailSize: {
height: 768,
width: 1366
}
}).then(sources => {
for (let s in sources) {
const content = sources[s].thumbnail.toPNG()
console.log(content)
}
})

How to fix images not loading in phaser.js

Whenever I try to load images into phaser they always appear as a green box on my screen?
I've not only tried the root file path like normal, but also every file path imaginable, but it still never works?
I'm assuming you've already set up a web server.. Did you look at developer tools and check if there are any errors? On Google Chrome, right click your web page and hit inspect. Navigate to the Consoles Tab and look for errors. Be sure to also Log XMLHttpRequests, as these will indicate when the request for said image has been fulfilled (just click the Log XMLHttpRequests checkbox).
Did any of the above solutions work for you? For me, I've used a Simple HTTP Server with Python. I was referencing my images correctly and had my web server hosted correctly. When using developer tools, there were no error messages.. I was banging my head against the wall for hours. The Phaser API was not able to tell what the local directory (http://192.168.0.2:8080/) was from the webpage from some reason.
I fixed my issue by using the following path for my images:
'http://192.168.0.2:8080/assets/sky.png'
where 192.168.0.2 was my local IP address hosting the server & 8080 was the port I was using for communications
Alternative to adding that lengthy file path for each of your images, you can call the this.load.setBaseURL('http://192.168.0.2:8080') function in combination with what you already have.
For example, see the following code:
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 200 }
}
},
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload ()
{
console.log('preload');
this.load.setBaseURL('http://192.168.0.2:8080');
this.load.image('bombP','bowmb.png');
this.load.image('einMary','/bowmb.png');
}
function create ()
{
console.log('create');
this.add.image(126, 119, 'bombP');
this.add.image(222,269,'einMary');
//var s = game.add.sprite(80,0,'einMary');
//s.rotation=0.219;
}
I should start by checking those two points below :
Check if the image has the right path to the file
Check if the 'key' you are using is the right one

Not allowed to load local resource: Ionic3(ios)

I am getting this issue
Not allowed to load local resource: file:///var/mobile/Containers/Data/Application/AB6EABD9-CAAF-4AE5-91F9-D8042B34EA87/tmp/cdv_photo_002.jpg
My code looks like
let cameraOptions = {
quality: 50,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(cameraOptions).then((imageData) => {
this.myImage = imageData;
})
In android device it works fine but in ios i am not able to avoid this issue i am sure it is due to some security issue it would be great some one help me.
I think something like this might work for you:
if (isIos()) {
itemSrc = itemSrc.replace(/^file:\/\//, '');
}
Based off of another thread I saw:
iOS camera plugin returns source with protocol for new captures but when using it in your HTML to set the source of an element like img or video you need to remove protocol
You can read more about it here: Ionic 3: File_URI Not allowed to load local resource IOS
I hope that helps!

Save canvas image on local mobile storage for IOS/Android

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

JsQRCode reader not working properly

I am using JSQRCode JS library to decode QR codes.
I found that it works just fine if I take pictures of the QR code from really close.
If I take the picture from a bit farther it is not able to decode the code.
NOTE: The code-decoding library is used within a Sencha Touch 2 app. The picture is taken using the Ext.device.Camera API that gives access to the phone camera.
Has anybody had similar problems?
Any possible solution or alternative way to reach the goal (taking picture + QR decoding)?
Any suggestion/comment is very appreciated!
Thank you very much!
Here is the code I'm running:
Ext.device.Camera.capture({
success: function(fileURI) {
// reassigning for test purposes
//fileURI = './resources/images/qrTemp.png';
console.log('Camera Success');
var imageView = Ext.getCmp('cameraImg');
imageView.setSrc(fileURI);
qrcode.decode(fileURI);
},
failure: function() {
console.log('Camera failure');
},
quality: 100,
source: 'camera'
}, /*scope*/ this, /*destination*/ 'file', /*encoding*/ 'png');
...
qrcode.callback = function(data){
window.alert('QRCode callback: '+ data);
};
UPDATE: just found out the problem is that the camera API from sencha touch is returning a very small image (although supposed to return a bigger one), so the code reader lib is not able to decode!
Anyone has faced this Sencha Touch problem?

Categories

Resources