So far I have got the camera api working for my app, to which the camera is opened when a button is clicked and once the image is taken it is displayed on the page.
My next step is to store the image into my sqlite database within a table. Creating the database is no problem as I already have a couple of other tables used for other parts of the app which work fine, it's just finding out how to store the image into the database.
Can someone provide some assistance here?
Camera Function:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.getElementById("btnCamera").onclick = function() {
navigator.camera.getPicture(function (imageUri) {
var lastPhotoContainer = document.getElementById("lastPhoto");
alert("Hot stuff!");
lastPhotoContainer.innerHTML = "<img src='" + imageUri + "' style='width: 75%;' />";
}, null, null);
};
}
HTML:
<div data-role="page" id="page7" data-theme="d">
<div data-role="header">
Sign ut
<h1>SoccerMeet</h1>
</div>
<div data-role="main" class="ui-content">
<input id="btnCamera" type="button" value="Camera photo" />
<p id="lastPhoto"></p>
</div>
<div data-role="footer">
<h2>© Gallery</h2>
</div>
</div>
UPDATED Script:
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2 * 1024 * 1024);
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Gallery (id INTEGER PRIMARY KEY, myImage BLOB)');
}, errorE, successS);
}
function successS() {
alert("Camera database ready!");
document.getElementById("btnCamera").onclick = function() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
};
}
function onSuccess(tx, imageData) {
alert("Camera test 1");
var image = document.getElementById("lastPhoto");
image.src = "data:image/jpeg;base64," + imageData;
base64imageData = imageData;
var _Query3 = ("INSERT INTO Gallery(myImage) values ('" + base64imageData + "')");
alert(_Query3);
tx.executeSql(_Query3);
}
/* function successCamera() {
navigator.notification.alert("Image has been stored", null, "Information", "ok");
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#page4" );
} */
function onFail(message) {
alert('Failed because: ' + message);
}
function errorE(err) {
alert("Error processing SQL: " + err.code);
}
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.getElementById("btnCamera").onclick = function() {
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
};
}
function onSuccess(imageData){
var image = document.getElementById("lastPhoto");
image.src = "data:image/jpeg;base64," + imageData;
//the imageData is a base64 representation of the image.
base64imageData=imageData;// this variable is a global variable and when ever asked for u can send it to SQL Operation class for storing.
}
function onFail(message) {
alert('Failed because: ' + message);
}
Related
I am developing a cross platform application using cordova.
I need to insert image inside sqlite. I am getting lots of code for android but I find it difficult to do with javascript. I am getting err.code:5 when I run the following code in my iPhone.
document.addEventListener("deviceready", onDeviceReady, false);
var img;
var currentRow;
var b = new Blob();
function previewFile() {
// var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
// var package_name = document.getElementById("pr").value;
reader.onloadend = function () {
// img = reader.result;
if(file.type.match('image.*'))
{
img = reader.result;
// ref.push({"image":image,"service":arr,"package_name":package_name});
}
else
{
alert("select an image file");
}
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
var image1 = encodeURI(img);
// var b = new Blob();
b = image1;
console.log(b);
console.log(image1);
//document.write('<img src="'+image+'"/>');
}
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id INTEGER PRIMARY KEY AUTOINCREMENT, name,number,image BLOB)');
}
function insertDB(tx) {
tx.executeSql('INSERT INTO DEMO (name,number,image) VALUES ("' +document.getElementById("txtName").value
+'","'+document.getElementById("txtNumber").value+'","' +b+ '")');
}
function goInsert() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(insertDB, errorCB, successCB);
}
My html code:
<input type="file" onchange="previewFile()">
<button onclick="goInsert()">Insert</button>
How to do this. Can someone help me? Thanks in advance...
Convert your image (in memory) to a byte[] and then save it your sql db as varbinary(max).
Inserting blob into database will make your application slow as well as laggy, instead save the path of the selected picture into the database.
And when you want to upload the image to the server use
fileupload feature of cordova.
If you are getting image from server than download that image locally and save that path into the database
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem)
{
fileSystem.root.getFile(
"dummy.html", {create : true, exclusive : false},
function gotFileEntry(fileEntry)
{
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile)
{
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error)
{
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);
I'm developing an application in Cordova. This app should be able to capture a video when you press the capture button, and then upload it on a specific server.
But I have a problem with the capture API. When I run it on emulator or a physical device, nothing happens, and on ripple, an error is returned.
My HTML code is here
<div class="button">
<div class="button1">
<button id="captureVideo" class="btn btn-lg btn-primary">launch a capture</button>
</div>
</div>
And my js
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("captureVideo").addEventListener("click", function () {
document.addEventListener("deviceready", onDeviceReady, false);
});
})
function onDeviceReady() {
console.log(navigator.device.capture);
navigator.device.capture.captureVideo(captureSuccess, captureError, { limit: 1 });
console.log("Record launched !");
}
// Called when capture operation is finished
function captureSuccess(mediaFiles) {
navigator.notification.alert("Capture Success");
/*var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}*/
}
// Called if something bad happens
function captureError(error) {
navigator.notification.alert("Capture failed");
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// Upload files to server
/*function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function (result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function (error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}*/
Thanks a lot for your answer :)
As demanded, I put my code directly here instead of pastebin.
Finally found ! It was cause my plugin wasn't loaded in the app.
I want to take a photo by using device camera and it will be stored in the some type of thumbnail:
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function onPhotoDataSuccessFront(imageData) {
var smallImageFront = document.getElementById('smallImageFront');
smallImageFront.style.display = 'block';
smallImageFront.src = "data:image/jpeg;base64," + imageData;
$('#btnFrontDiv').text('Retake Front');
}
As you can see I use navigator.camera which is avaliable in cordova/phonegap.
I want to capture photo by using cordova or plain javascript.
Thanks for any advice.
Try this one
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title> Cmaer</title>
<script type="text/javascript" src="cordova.js" ></script>
<script type="text/javascript">
var pictureSource,destinationType;
document.addEventListener("deviceready",loaded,false);
function loaded() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function getPhoto(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageData;
}
function capturePhoto() {
navigator.camera.getPicture(getPhoto, onFail, { quality: 50 });
}
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
</body>
</html>
Reference
Capture and Upload image using phonegap
function uploadImage(){
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: Camera.DestinationType.FILE_URI });
}
function onFailcapturePhoto(message) {
console.log("Message = " + message);
}
function uploadPhoto(imageURI) {
var imagefile = imageURI;
$('#imageId').attr('src', imagefile);
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}
You may use HTML5 which has brought a surge of access to device hardware.
See this Link Capturing Audio & Video in HTML5
Note :getUserMedia() has been supported since Chrome 21, Opera 18, and Firefox 17.
Please go through support browser list (for mobile phone also) before implementing this.
How do you get a path from a file object which is returned from an html5 input field?
Basically the phonegap app is setup to go online and download a sound file from a thirdparty website, then browse to the downloaded file and move it to the local directory. (short < 1 sec sound files).
The problem is that file objects attribute .fullPath is undefined. and getFile takes a path input, not an [object File] input.
From the following code:
<input style="opacity:0;" type="file" name="soundInput" id="soundInput"/>
<script type="text/javascript" charset="utf-8">
var soundInput = document.getElementById('soundInput');
soundInput.addEventListener('change', function(){handleFileSelect(type);}, false);
soundInput.click();
function handleFileSelect() {
var file = this.files[0]; // FileList object
var type = isThumpy;
alert("file = " + file.name + "\n full path = " + file.fullPath);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
gotFS(fs,file,type);
}, fail);
}
function fail(error) {
alert("error " + error.code);
}
function gotFS(fileSystem, file, type) {
alert("got filesystem");
var flags = {create: false, exclusive: false};
fileSystem.root.getFile(file, flags, function(fe){
gotFileEntry(type,fe);
},fail);
}
function gotFileEntry(type, fileEntry) {
alert("got fileEntry");
fileEntry.copyTo(path, function(fe){successfulCopy(type, fe);}, fail);
}
function successfulCopy(type, fileEntry) {
alert("copy success");
setSoundByUri(type, fileEntry.name)
}
</script>
It doesn't get past "got filesystem", and it doesn't throw an error ("error " + error.code). Please help.
You can not get the path data from a file input. File inputs are read only. Try changing the approach. Use the phoneGap fileEntry to create the new file and write data from the file input to it.
like this:
<script type="text/javascript" charset="utf-8">
function handleFileSelect(type) {
var file = this.files[0]; // FileList object
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
gotFS(fs,file,type);
}, fail);
}
function gotFS(fileSystem, file, type) {
var flags = {create: true, exclusive: false};
fileSystem.root.getFile(file.name, flags, function(fe) {gotFileEntry(fe, file, type);}, fail);
}
function gotFileEntry(fileEntry, file, type) {
fileEntry.createWriter(function(w){gotFileWriter(w, file, type);}, fail);
}
function gotFileWriter(fileWriter, file, type) {
fileWriter.onwriteend = function(evt){setSoundByUri(type, path + file.name);};
var reader = new FileReader();
reader.onload = function(event) {
var rawData = event.target.result;
fileWriter.write(rawData);
};
reader.onerror = function(event){
alert("error, file could not be read" + event.target.error.code);
};
reader.readAsArrayBuffer(file);
}
function fail(error) {
alert("error " + error.code);
if (error.code == FileError.PATH_EXISTS_ERR){
alert("The file already exists.");
}
}
</script>
I am trying to set up database to store user image and name. I have put the code up on jsfiddle http://jsfiddle.net/Inkers/dZJnG/. When I run the code on my device I get a number of errors. Code here too:
HTML
<body onload="onDeviceReady()">
<h3>Enter name and picture</h3>
<div id= "userProfile">
<button onclick="takePhoto();">Capture Photo</button> <br>
<img style="display:none;width:100px;height:100px;" id="smallImage" src="" />
<p></p>
<input id="userName" type="text" placeholder="name">
<input id="saveProfile" type="button" value="Save" onClick="insertEntry();""location.href='Createtask.html'"> <br>
<input id="allUsers" type="button" value="All users" onClick="queryDB();"> <br>
</div>
JS
function init(){
document.addEventListener("deviceready", onDeviceReady, false);
}
var pictureSource; // picture source
var destinationType;
function onDeviceReady() {
var db = window.openDatabase("database", "1.0", "Profiles", 5000);
if(db) {
console.log('The database is working');
alert('The database is working');
db.transaction(createTable, insertEntry, errorCB, successCB); // only do stuff if db exists
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
else{
console.log('There is a problem');
}
}
function takePhoto(){
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
}
function onPhotoDataSuccess(imageData) {
console.log(imageData);
// Get image handle
var smallImage = document.getElementById('smallImage');
// Unhide image elements
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function createTable(tx) {
var sqlStr =('CREATE TABLE IF NONE EXISTS USERS(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, image BLOB)');
tx.executeSql(sqlStr,[],successCB, errorCB);
console.log("Users table created");
}
function insertEntry(tx){
var tmpName = document.getElementById("userName").value;
var tmpImage = document.getElementById("smallImage").src;
var sqlStr=('INSERT INTO USERS (name, image) VALUES (?,?)');
tx.executeSql = (sqlStr, [tmpName, tmpImage], onSqlSuccess, errorCB);
alert('record entered');
}
// Query the success callback
function onSqlSuccess(tx, res){
var len = results.rows.length;
console.log("USERS table: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data);
}
}
// Query the database
//
function queryDB() {
var sqlStr = ('SELECT * FROM USERS; ORDER BY id ASC');
database.transaction(function (tx){
tx.executeSql(sqlStr,[],onSqlSuccess, errorCB);
})
}
// Transaction error callback
//
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
// Transaction success callback
//
function successCB() {
console.log('');
}