I tried many ways and referred many questions here but still my camera is not launching.Help me in this.I checked manifest and config xml files.there is no error in that.Can any one give me working example for cordova camera.
<script>
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoURISuccess(imageURI) {
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}
function capturePhoto() {
alert("varun");
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA });
}
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
Related
I am having problems with Apache Cordova and Android. I have some code to send one picture to server, from an Android cellphone, but it doesn't work. I have tested the ajax and php code on the server, and it works, but when I try from the cellphone it does not.
app.js:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
var image = "";
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
destinationType: destinationType.DATA_URL
});
}
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
image = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function submitFunction() {
var dataString = 'image='+encodeURIComponent(image);
$.ajax({
type: "POST",
url: "//192.0.1.2/testing/test.php",
data: dataString,
cache: false,
error: function(){
ShowStatus( "AJAX - error()" );
document.getElementById("result").innerHTML = 'Error';
},
beforeSend: function() {
document.getElementById("result").innerHTML = 'Enviando Data';
},
success: function(result){
document.getElementById("result").innerHTML = result;
}
});
}
test.php:
<?php
header('Access-Control-Allow-Origin: *');
require'connection.php';
$mysqli = conectarse();
$res = $mysqli->query("INSERT INTO imagenes (image) VALUES
('".$_POST['image']."')");
$mysqli->query($res);
if (!$res) {
printf("Errormessage: %sn", $mysqli->error);
}
?>
This code has the following dependencies:
cordova.js
jquery.min.js
For Android in PhoneGap 2.8.0:
I need to get image from phone gallery and need to insert in app...
My code:
HEAD:
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<link rel="stylesheet" href="css/jquery.mobile-1.0rc1.min.css" />
<link rel="stylesheet" href="css/styles.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.0rc1.min.js"></script>
<script src="js/cordova.js"></script>
HTML:
<button data-theme="d" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Browse Photos</button>
<div id="photos"></div>
SCRIPT:
function onPhotoURISuccess(imageURI) {
var img = $('<img />');
img.attr('src', imageURI);
img.appendTo('#photos');
}
But its not working....how can i do this?
error that i got in console
file:///android_asser/www/index.html: Uncaught typeerror : cannot read property 'PHOTOLIBRARY' of undefined
Uncaught typeerror : [Object Object] has no method 'split' at file:///android_asset/www/js/jquery.mobile-1.0rc1.min.js
after i removed the jquery and jquery-mobile its working... any problem with jQuery with phonegap?
Thanks in advance
I have implemented this code...recently..check this
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady()
{
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoURISuccess(imageURI)
{
console.log(imageURI);
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}
function onPhotoDataSuccess(imageURI)
{
var imgProfile = document.getElementById('imgProfile');
imgProfile.src = imageURI;
if(sessionStorage.isprofileimage==1)
{
getLocation();
}
movePic(imageURI);
}
function onFail(message)
{
alert('Failed because: ' + message);
}
function movePic(file)
{
window.resolveLocalFileSystemURI(file, resolveOnSuccess, resOnError);
}
function resolveOnSuccess(entry)
{
var d = new Date();
var n = d.getTime();
var newFileName = n + ".jpg";
var myFolderApp = "MyAppFolder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys)
{
fileSys.root.getDirectory( myFolderApp,
{create:true, exclusive: false},
function(directory)
{
entry.moveTo(directory, newFileName, successMove, resOnError);
},
resOnError);
},
resOnError);
}
function successMove(entry)
{
sessionStorage.setItem('imagepath', entry.fullPath);
}
function resOnError(error)
{
alert(error.code);
}
function capturePhotoEdit()
{
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
function getPhoto(source)
{
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
</script>
My html
<button onclick="capturePhoto();">Capture Photo</button>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Gallery!!</button>
try this link i hope it might be help you
http://tympanus.net/codrops/2010/05/27/awesome-mobile-image-gallery-web-app/
See the api
http://docs.phonegap.com/en/2.8.0/index.html
and you also try like
if Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected.
Hi blow is working code for Camera and gallery.
I use different function for both purpose because using the device capture you can capture the multiple image .
i hope it will help you.
<select>
<option>--Select--</option>
<option onclick="GetImage(1)">Camera</option>
<option onclick="GetImage(2)">Library</option>
<option onclick="GetImage(3)">Album</option>
</select>
//// fuction to select which type of upload you want to perform
GetImage(index)
{
switch (index)
{
case 1:
captureImage();
break;
case 2:
getPhoto('pictureSource.PHOTOLIBRARY');
break;
case 3:
getPhoto('pictureSource.SAVEDPHOTOALBUM');
break;
}
}
//// fuction calle from camera capture success
function captureSuccess(mediaFiles) {
var i, len;
debugger;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
//// function to camputure image from camera
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
navigator.device.capture.captureImage(captureSuccess, capturetError, { limit: 1 });
}
//// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
////your s url
var objUrl =www.xyx.com;
ft.upload(path,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
//// fuction to capture image from Gallery or PHOTOLIBRARY
function getPhoto(source) {
// Retrieve image file location from specified source
var cameraSource;
if (source = "pictureSource.PHOTOLIBRARY") {
cameraSource = pictureSource.PHOTOLIBRARY;
}
if (source = "pictureSource.PHOTOLIBRARY") {
cameraSource = pictureSource.SAVEDPHOTOALBUM;
}
navigator.camera.getPicture(CaptureImageSuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: cameraSource
});
}
//// Upload files to server from Gallery
function CaptureImageSuccess(fileURI) {
////your service url
var objUrl =www.xyx.com;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1)+".jpg";
options.mimeType = "image/jpeg";
options.params = {}; // if we need to send parameters to the server request
var ft = new FileTransfer();
//ft.upload(fileURI, encodeURI(), win, fail, options);
ft.upload(fileURI,
objUrl,
function (result) {
alert("Success");
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
options);
};
Here is my phonegap code. This code is for taking the picture as well as save the picture also:
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo and Save</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready to be used!
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
var date = ""
var d = new Date();
date = "" + d.getDate() + "-" + (d.getMonth() + 1) + "-"
+ d.getFullYear();
alert(date)
//alert(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;
alert("data:image/jpeg;base64," + imageData)
//This part is for saving the capture photo
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
function gotFS(fileSystem) {
alert("image/" + date + ".jpeg")
fileSystem.root.getFile("image/" + date + ".jpeg", {
create : true,
exclusive : false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
var data = "data:image/jpeg;base64," + imageData;
writer.write(data);
}
function fail(error) {
alert("error")
console.log(error.code);
}
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
var largeImage = document.getElementById('largeImage');
// Unhide image elements
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality : 50,
destinationType : destinationType.DATA_URL
});
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality : 20,
allowEdit : true,
destinationType : destinationType.DATA_URL
});
}
// A button will call this function
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality : 50,
destinationType : destinationType.FILE_URI,
sourceType : source
});
}
// Called if something bad happens.
function onFail(message) {
alert('Failed because: ' + message);
}
function savePhoto(source) {
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button>
<br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button>
<br>
<button onclick="savePhoto();">Save The Photo In Server</button>
<br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From
Photo Library</button>
<br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From
PhotoAlbum</button>
<br>
<img style="display: none; width: 60px; height: 60px;" id="smallImage"
src="" />
<img style="display: none;" id="largeImage" src="" />
</body>
</html>
I am taking a picture and trying to save it like this but it is saving as a file not as a picture(binary).so after saving the picture its not opening.How can i save it with proper fromat so that i can open it as a picture ?
I did it this way:
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI, });
}
function onPhotoDataSuccess(imageURI) {
var gotFileEntry = function(fileEntry) {
//alert("got image file entry: " + fileEntry.fullPath);
var gotFileSystem = function(fileSystem) {
fileSystem.root.getDirectory("MyAppFolder", {
create : true
}, function(dataDir) {
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
console.log("Saved image" + dataDir);
// copy the file
fileEntry.moveTo(dataDir, newFileName, null, fsFail);
}, dirFail);
};
// get file system to copy or move image file to
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileSystem,
fsFail);
};
// resolve file system for image
window.resolveLocalFileSystemURI(imageURI, gotFileEntry, fsFail);
// file system fail
var fsFail = function(error) {
alert("failed with error code: " + error.code);
};
var dirFail = function(error) {
alert("Directory error code: " + error.code);
};
}
Hope it helps you!
If you are ok to save image in photo gallery, then try following code :
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality: 50,
destinationType : destinationType.FILE_URI,
saveToPhotoAlbum : true,
});
}
function save(){
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("pic.jpg", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
var photo = document.getElementById("image");
writer.write(photo.value);
}
function fail(error) {
console.log(error.code);
}
<script type="text/javascript" charset="utf-8">
var pictureSource; // Picture source
var destinationType; // Sets the format of returned value
// Wait for PhoneGap to connect with the device
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready to be used!
function onDeviceReady()
{
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function capturePhoto() {
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 25, destinationType:
Camera.DestinationType.FILE_URI });
}
function onPhotoURISuccess(imageURI) {
createFileEntry(imageURI);
}
function createFileEntry(imageURI) {
window.resolveLocalFileSystemURI(imageURI, copyPhoto, fail);
}
function copyPhoto(fileEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory("photos", {create: true, exclusive: false},
function(dir) {
fileEntry.copyTo(dir, "file.jpg", onCopySuccess, fail);
}, fail);
}, fail);
}
function onCopySuccess(entry) {
console.log(entry.fullPath)
}
function fail(error) {
console.log(error.code);
}
</script>
You should use the PhoneGap 2.0.0 camera object. The documentation provides a full photo capturing example.
Furthermore the navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] ); takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded String or as the URI of an image file.
I hope this helps.
How can I specify the name and destination of captured photo using Phonegap? Couldn't find this info anywhere. Right now it just goes to /sdcard/pic.jpg.
Here's what I have so far:
function capturePhoto() {
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.style.display = 'block';
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
try content://media/external/images/media/n
where n is the image number you are trying to call (1,2,3, etc)