choose image from android image gallery - PhoneGap not working - android

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);
};

Related

Cordova camera not launching

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>

Send a picture using cordova on android

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

Phonegap capture photo and upload to server

I am facing a problem here for my code. Whenever I put in my function uploadPhoto, the function capturePhotoWithFile would not work(I pressed the button but nothing happened). However when I remove the function uploadPhoto, the function capturePhotoWithFile would work again(I could pressed the button and take a photo).
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1"/>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoFileSuccess(imageData) {
console.log(JSON.stringify(imageData));
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageData;
}
function capturePhotoWithFile() {
navigator.camera.getPicture(onPhotoFileSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}
function onFail(message) {
alert('Failed because: ' + message);
}
function uploadPhoto() {
var imageData = document.getElementById('smallImage').getAttribute("src");
if (!imageData) {
alert('Please select an image first.');
return;
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageData.substr(imageData.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
}
var ft = new FileTransfer();
ft.upload(imageData, encodeURI("uploadtest.php"), win, fail, options);
}
function onFail(message) {
console.log('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert("Response =" + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
</head>
<body>
<button onclick="capturePhotoWithFile();">Capture Photo</button> <br>
<button onclick="uploadPhoto();">Upload</button> <br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
Try this way :
function getPictureFromCamera(){
navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType:Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
$('#camera-image').css({'background-image': 'url('+imageURI+')', 'background-size': '100%'});
}
function onFail(message) {
console.log('Failed to get an image');
}
}
function getPictureFromGallery(){
navigator.camera.getPicture(onSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY });
function onSuccess(imageURI) {
$('#camera-image').css({'background-image': 'url('+imageURI+')', 'background-size': '50%'});
}
function onFail(message) {
console.log('Failed to get an image');
}
}
OutPut:

phonegap android cannot read image file

I am developing hybrid using phonegap 3.3. I am using camera plugin to capture image and store into photo album which working fine. Later, I have to read image file from the device storage.
I am using the following code.
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, failFS);
function gotFS(fileSystem){
fileSystem.root.getFile(imageData, {create: true}, gotFileEntry, fail);
}
function gotFileEntry(){
fileEntry.file(gotFile,fail);
}
function gotFile(file){
alert(file.getParent().fullPath);
}
I am getting error in the first line. It is giving
FileError.ENCODING_ERR
I am not sure what I am doing wrong here. After, I have to move to another directory with new name. Could anyone help me to fix.
I am using camera plugin for capture images and file plugin to read files and directory.
--Sridhar
You can try with below code to capture and copy image
var pictureSource;
var destinationType;
var FileFolder = "";
var FileName = "";
var obj_imageCapture = {
capturePicture:function(imgFolder,imgName)
{
var image = imgFolder + imgName;
FileFolder = imgFolder;
FileName = imgName;
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
navigator.camera.getPicture(obj_imageCapture.onPhotoDataSuccess1, obj_imageCapture.onFail, {quality: 50, destinationType: destinationType.FILE_URI , saveToPhotoAlbum: true });
},
onPhotoDataSuccess1:function(imageData){
obj_imageCapture.createFileEntry(imageData);
},
createFileEntry:function(imageURI) {
window.resolveLocalFileSystemURI(imageURI, obj_imageCapture.copyPhoto, obj_imageCapture.onFFail);
},
copyPhoto:function(fileEntry) {
try
{
var ext = fileEntry.fullPath.substr(fileEntry.fullPath.lastIndexOf('.'));
var imageN = "";
if(FileName.indexOf('.') > 0)
{
imageN = FileName.substr(0,FileName.lastIndexOf('.')) + ext;
}
else
{
imageN = FileName + ext;
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory(FileFolder, {create: true, exclusive: false}, function(dir) {
fileEntry.copyTo(dir, imageN, obj_imageCapture.onCopySuccess, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}, obj_imageCapture.onFFail);
}
catch(ex)
{
alert(ex.message);
}
},
onCopySuccess:function(entry) {
var smallimage = document.getElementById("myimage");
smallimage.style.display = "block";
smallimage.src = entry.fullPath + "?rand=" + Math.random();
},
onFFail:function(message)
{
alert("Error in photo : " + message.message);
}
};
Above code might helpful to you

After taking a picture using phonegap (navigator.camera.getPicture) how can i store it in my local drive?

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);
}

Categories

Resources