Reading a saved image from sdcard using PhoneGap - jquery-mobile

I am saving a canvas image in sdcard.
I am saving it to the folder called Pictures, and trying to display it back on the device.
Now I have to retrieve it back and display it. I tried the following code:
Javascript
var ShowSavedImage = function(Imagename){
alert("in ShowSavedImage ");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);
}
function onFail(message) {
alert('Failed because: ' + message);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("Pictures/b64Image_1372901806166.png", {create: true}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = evt.target.result;
};
reader.readAsDataURL(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
HTML
<div data-role="page" id="SavedImage">
<div data-role="header" class= "header" data-position="fixed" data-tap-toggle="false" >
</div>
<div data-role="content" >
<center>
<h3 id="savedImageHeader"></h3>
<!-- <img src="" id="savedImageDisplay" style="display:none;height:auto; max-height:70%; width:auto; max-width:90%;"/> -->
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
</center>
</div>
</div>
When I tried this code I am getting following error
07-04 09:26:11.418: I/Web Console(22909): processMessage failed: Stack: TypeError: Cannot read property 'style' of null
07-04 09:26:11.418: I/Web Console(22909): at [object Object].<anonymous> (file:///android_asset/www/js/list.js:691:45)
07-04 09:26:11.418: I/Web Console(22909): at file:///android_asset/www/js/cordova-2.5.0.js:2549:20
07-04 09:26:11.418: I/Web Console(22909): at Object.captureReturnValue [as success] (file:///android_asset/www/js/cordova-2.5.0.js:847:20)
07-04 09:26:11.418: I/Web Console(22909): at Object.callbackFromNative (file:///android_asset/www/js/cordova-2.5.0.js:291:46)
07-04 09:26:11.418: I/Web Console(22909): at processMessage (file:///android_asset/www/js/cordova-2.5.0.js:964:21)
07-04 09:26:11.418: I/Web Console(22909): at Function.processMessages (file:///android_asset/www/js/cordova-2.5.0.js:1002:17)
07-04 09:26:11.418: I/Web Console(22909): at androidExec (file:///android_asset/www/js/cordova-2.5.0.js:856:21)
07-04 09:26:11.418: I/Web Console(22909): at [object Object].readAsDataURL (file:///android_asset/www/js/cordova-2.5.0.js:2528:5)
07-04 09:26:11.418: I/Web Console(22909): at readDataUrl (file:///android_asset/www/js/list.js:694:12)
07-04 09:26:11.418: I/Web Console(22909): at gotFile (file:///android_asset/www/js/list.js:683:5) at file:///android_asset/www/js/cordova-2.5.0.js:971
I am new to PhoneGap and I didn't understand what went wrong.
How to solve this?

I think that your issue not with phonegap, this is a pure js error, I think that your code is running before dom is built. so you may add any button then write your code onclick of this button and test. I think this will make you understand the issue

Related

Google Geochart only appears after a refresh

I am trying to integrate Google GeoChart to my rails application. In the view i simply copied-pasted the example from Google:
On top of the document i have the following:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700]
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
Then I add the div with the id:
<div id="regions_div" style="width: 100%; height: 500px;"></div>
But i get the following error:
VM17084:3 Uncaught TypeError: Cannot read property 'load' of undefined
at <anonymous>:3:21
at o.assignNewBody (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
at o.replaceBody (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
at turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6
at o.e.renderView (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
at o.render (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
at Function.e.render (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
at t.renderSnapshot (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
at t.render (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
at r.render (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:7)
The error disapears when I reload the page, which makes me thinks that it is related to Turbolinks.
Does anybody know how to fix this issue please ?
The page wasn't fully loaded when your javascript code started to run, google.charts was not available yet, hence the Cannot read property 'load' of undefined error.
Solution: Wrap your javascript code in a listener that fires when the page is loaded:
document.addEventListener("DOMContentLoaded", function(){
google.charts.load('current', {
// ...etc...
});
});
I ended up using the following:
setTimeout(function() {
google.charts.load('current', {
'packages': ['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var rubydata = JSON.parse('<%= #user_origin.to_json.html_safe -%>')
data = [["Country","Value"]].concat(rubydata)
var data = google.visualization.arrayToDataTable(data);
var options = {
legend: {position: 'none'},
colors: <%= raw #palette_final.to_json %>
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
} }, 1000);

Apache Cordova error uploading cropped image to server from IOS

On my IOS mobile application I am taking picture and then select a picture from gallery. After selecting this picture I am using ng-img-crop.js to crop this image and without saving this cropped image, trying to upload it to a server, the server side is C# WCF. (In this particular example I am trying to upload local IIS) But I am getting this error:
ERROR: {"code":1,"source":"data:image/png;base64,iVBORw0KGgoAAAANSUhE...","target":"http://11.111.11.111/wcf/OCRService.svc/upload","http_status":null,"body":null,"exception":null}
app.js (76,24)
Should I save this cropped image to the gallery before uploading to the server? Is there any way to upload it without saving?
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Security-Policy" content="connect-src 'self' http://11.111.11.111/wcf/OCRService.svc/upload 'unsafe-eval' 'unsafe-inline'; default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<title>LoTTo</title>-->
<!-- LoTTo references -->
<link href="css/ionicons.css" rel="stylesheet" />
<link href="css/ionic.css" rel="stylesheet" />
<link href="css/ng-img-crop.css" rel="stylesheet" />
<!-- Cordova reference, this is added to your app when it's built. -->
<script src="scripts/angular.min.js"></script>
<script src="scripts/ionic.bundle.js"></script>
<script src="scripts/ng-cordova.min.js"></script>
<script src="scripts/ng-img-crop.js"></script>
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/index.js"></script>
<script src="scripts/ng-file-upload-shim.min.js"></script>
<script src="scripts/ng-file-upload.min.js"></script>
<style>
.cropArea {
background: #E4E4E4;
overflow: hidden;
width: 300px;
height: 300px;
}
.croppedArea {
background: #E4E4E4;
overflow: hidden;
width: 300px;
}
</style>
</head>
<body ng-app="starter">
<ion-header-bar class="bar bar-header bar-light">
<h1 class="title">LoTTo</h1>
</ion-header-bar>
<ion-content ng-controller="ExampleController" padding="true">
<button class="button button-full button-balanced icon-right ion-ios-camera" ng-click="takePhoto()">
Resim Çek
</button>
<button class="button button-full button-balanced icon-right ion-images" ng-click="choosePhoto()">
Resim Seç
</button>
<center>
<div class="cropArea">
<img-crop image="myImage" result-image="myCroppedImage" chargement="'Loading'"
area-type="rectangle"
area-min-size="50"
result-image-format="image/jpeg"
result-image-quality="1"
result-image-size="{w:300, h:50}"></img-crop>
</div>
<div ng-show="myImage !== undefined">Gönderilecek Resim:</div>
<div class="croppedArea"><img ng-src="{{myCroppedImage}}" ng-show="myImage !== undefined" id="image" /></div>
</center>
<button class="button button-full button-balanced icon-right ion-images" ng-click="upload(myCroppedImage);" ng-if="myImage !== undefined">
Resim Yükle
</button>
</ion-content>
</body>
</html>
Here is the app.js:
angular.module('starter', ['ionic', 'ngCordova', 'ngImgCrop', 'ngFileUpload'])
.controller("ExampleController", ['$scope', '$cordovaCamera', 'Upload', '$timeout', '$cordovaFileTransfer', function ($scope, $cordovaCamera, Upload, $timeout, $cordovaFileTransfer) {
$scope.takePhoto = function () {
var options = {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
}, function (err) {
console.log(err);
alert(err);
});
}
$scope.choosePhoto = function () {
var options = {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
$scope.myImage = $scope.imgURI;
}, function (err) {
console.log(err);
alert(err);
});
}
$scope.myCroppedImage = '';
$scope.upload = function (dataUrl) {
Upload.upload({
url: 'http://192.168.1.20/wcf/upload',
data: {
file: Upload.dataUrltoBlob(dataUrl)
},
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
console.log(response.data);
alert(response.data);
});
console.log(response.data);
}, function (response) {
if (response.status > 0) $scope.errorMsg = response.status
+ ': ' + response.data;
alert(response.status);
});
}
}]);
Edit 1: How to add Access-Control-Allow-Origin to my mobile app?
Edit 2: Changed the upload section
Best Regards.
This example might help you:
Check this jsfiddle: [http://jsfiddle.net/xxo3sk41/1/][1]
code :
var app = angular.module('fileUpload', ['ngFileUpload', 'ngImgCrop']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.upload = function (dataUrl) {
Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {
file: Upload.dataUrltoBlob(dataUrl)
},
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
}, function (response) {
if (response.status > 0) $scope.errorMsg = response.status
+ ': ' + response.data;
}, function (evt) {
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
});
}
}]);

Apache Cordova failed to load resource: The server responded with a status of 415 while uploading image to WCF service from iOS

I am trying to upload an image from my iOS mobile app to a WCF service which is hosted on local IIS. I am getting this error:
Failed to load resource: the server responded with a status of 415
(Cannot process the message because the content type
'multipart/form-data; boundary=----WebKitFormBoundaryPUTlLsy2dLriRyDm'
was not the expected type 'multipart/related;
type="application/xop+xml"'.) OCRService.svc (0,0)
I couldn't find out how to fix this. Any ideas?
Here is my Apache Cordova JavaScript:
angular.module('starter', ['ionic', 'ngCordova', 'ngImgCrop', 'ngFileUpload'])
.controller("ExampleController", ['$scope', '$cordovaCamera', 'Upload', '$timeout', function ($scope, $cordovaCamera, Upload, $timeout) {
$scope.takePhoto = function () {
var options = {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
}, function (err) {
console.log(err);
alert(err);
});
}
$scope.choosePhoto = function () {
var options = {
quality: 100,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 300,
targetHeight: 300,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.imgURI = "data:image/jpeg;base64," + imageData;
$scope.myImage = $scope.imgURI;
}, function (err) {
console.log(err);
alert(err);
});
}
$scope.myCroppedImage = '';
$scope.upload = function (dataUrl) {
Upload.upload({
url: 'http://192.168.1.20/wcf/OCRService.svc',
file: "data:image/jpeg;base64," + dataUrl
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
console.log(response.data);
alert(response.data);
});
}, function (response) {
if (response.status > 0) $scope.errorMsg = response.status
+ ': ' + response.data;
alert(response.status);
});
}
}]);
Here is my HTML:
<body ng-app="starter">
<ion-header-bar class="bar bar-header bar-light">
<h1 class="title">LoTTo</h1>
</ion-header-bar>
<ion-content ng-controller="ExampleController" padding="true">
<button class="button button-full button-balanced icon-right ion-ios-camera" ng-click="takePhoto()">
Resim Çek
</button>
<button class="button button-full button-balanced icon-right ion-images" ng-click="choosePhoto()">
Resim Seç
</button>
<center>
<div class="cropArea">
<img-crop image="myImage" result-image="myCroppedImage" chargement="'Loading'"
area-type="rectangle"
area-min-size="50"
result-image-format="image/jpeg"
result-image-quality="1"
result-image-size="{w:300, h:50}"></img-crop>
</div>
<div ng-show="myImage !== undefined">Gönderilecek Resim:</div>
<div><img ng-src="{{myCroppedImage}}" ng-show="myImage !== undefined" id="image" /></div>
</center>
<button class="button button-full button-balanced icon-right ion-images" ng-click="upload(myCroppedImage)" ng-if="myImage !== undefined">
Resim Yükle
</button>
</ion-content>
</body>
Here is my WCF Service Contract related part:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "OCRImage?stream={stream}")]
string OCRImage(Stream stream);
Here is my WCF class related part:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class LoTToOCR : IOCRService
Here is my WCF web config related part:
<configuration>
<system.serviceModel>
<bindings>
<!-- pick whichever binding you want .... -->
<basicHttpBinding>
<binding name="OCRServiceSoap"
closeTimeout="00:10:00" openTimeout="00:10:00"
receiveTimeout="00:10:00" sendTimeout="00:10:00"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Mtom">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="basic" name="LoTToOCRService.LoTToOCR">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="OCRServiceSoap"
contract="LoTToOCRService.IOCRService" />
<host>
<baseAddresses>
<!--<add baseAddress=
"http://192.168.199.1/wcf/OCRService.svc"/>-->
<add baseAddress=
"http://192.168.1.20/wcf/OCRService.svc"/>
</baseAddresses>
</host>
</service>
</services>

Ionic Cordova Printer error

i am trying to use the cordova printer plugin from: https://github.com/katzer/cordova-plugin-printer/tree/master
I have followed the installation instructions and have this in index.html:
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
Here is my controller call:
$scope.printTable = function(){
$ionicPlatform.ready(function() {
cordova.plugins.printer.isAvailable(
function (isAvailable) {
alert(isAvailable ? 'Service is available' : 'Service NOT available');
});
})
};
i get this error on phonegap app:
Error: undefined is not an object (evaluating 'cordova.plugins.printer')
I have this added in my config.xml file:
<gap:plugin name="de.appplant.cordova.plugin.printer" version="0.7.0" />
What am i missing here
$scope.print = function() {
if ($cordovaPrinter.isAvailable()) {
$cordovaPrinter.print(//type what to display);
} else {
alert("Printing is not available on device");
}
}
just try like this

open camera in iPad phoneGap application

I am using following function for capture image.
function openCamera() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
},
function(e) {
console.log("Error getting picture: " + e);
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
And I am using following js of phonegap
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
I am using following image tag for captured image
<img style="width: 128px; height: 160px; visibility:hidden; display:none;" id="camera_image" src="" />
But its not open camera.Am not know what is the issue.?
try adding the sourceType too..
sourceType : navigator.camera.PictureSourceType.CAMERA

Resources