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:
Related
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>
I'm developing an application that will have to send images to an external server, downloaded and installed the file-transfer , however it stopped working appearing error 3, I am running xampp on my local network, below is my code, I took it from the plugin documentation
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>File Transfer Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
// Retrieve image file location from specified source
navigator.camera.getPicture(
uploadPhoto,
function(message) { alert('get picture failed'); },
{
quality : 50,
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://192.168.0.105/upload/index.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("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>
<h1>Example</h1>
<p>Upload File</p>
</body>
</html>
PHP:
<?php
$new_image_name = strtolower($_FILES['file']['name']);
move_uploaded_file($_FILES["file"]["tmp_name"], "images/".$new_image_name);
Add the header object to option once.
Solution from here
options.headers = {
Connection: "close"
}
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);
}
I am a phonegap newbie. I am trying to read and image file from sdcard in android using
phonegap official tutorial. The problem is that the image is not being displayed instead a question mark appears in its place.
My Code:
var pictureSource;
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
document.getElementById("test").innerHTML="onready about to request";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);}
function onFail(message) {
alert('Failed because: ' + message);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("1.jpg", null, 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 = reader.readAsDataURL(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>
edit:
Using API 16 and min-sdk8
"smallImage" is a tag it's working fine with onphotodatasuccess. So, camera is not a problem here. Everything related to camera functions is ok. Reading from sdcard is posing a problem at the assignment statement.
document.getElementById("smallImage").src = reader.readAsDataURL(file); if I add this i get the string and unknown chromium error -6, else i see the usual image converted string.
Thanks
Here is a working example :
EDITED:
<!DOCTYPE html>
<html>
<head>
<title>Pick Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, onFail);
}
function onFail(message) {
alert('Failed because: ' + message);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("1.jpg", {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);
}
</script>
</head>
<body>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
This will allow you to pick any specified image from sdcard.
Hope this helps you.
Thanks.
try this:
<script>
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady(){
//This file have to exist
var location= "file:///storage/emulated/0/DCIM/Camera/20141105_124208.jpg";
window.resolveLocalFileSystemURL(location, function(oFile) {
oFile.file(function(readyFile) {
var reader= new FileReader();
reader.onloadend= function(evt) {
document.getElementById("smallImage").style.display='block';
document.getElementById("smallImage").src = evt.target.result;
};
reader.readAsDataURL(readyFile);
});
}, function(err){
console.log('### ERR: filesystem.directoryUp() - ' + (JSON.stringify(err)));
});
</script>