i would like to ask you..
i have a code... using phonegap.. but i was confused about how to call / crop the image after take it from camera / file manager...
here the code...
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="js/jquery.mobile-1.0.min.css" />
<script src="js/jquery-1.6.4.min.js"></script>
<script src="js/jquery.mobile-1.0.min.js"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.1.0.js"></script>
<script type="text/javascript" charset="utf-8">
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
window.location.hash = "#page2";
/*document.getElementById('camera_status').innerHTML = "Success"; */
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, targetWidth: 1153, targetHeight: 385
}
);
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
window.location.hash = "#page2";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, targetWidth: 1153, targetHeight: 385, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
$.mobile.showPageLoadingMsg();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
viewUploadedPictures();
$.mobile.hidePageLoadingMsg();
window.location.hash = "#page3";
}, function(error) {
$.mobile.hidePageLoadingMsg();
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
</head>
<body onload="init();">
<!-- Page 1 -->
<div data-role="page" id="page1">
<!-- Page 1 Header -->
<div data-role="header">
<h1>Ambil Gambar</h1>
</div>
<!-- Page 1 Content -->
<div data-role="content">
<center>
<a href="javascript:void(0)" onclick="takePicture();">
<img src="image/camera.png" width="150px" height="150px">
</a>
<br>
<br>
<b>Atau</b>
<br>
<br>
<a href="javascript:void(0)" onclick="selectPicture();">
<img src="image/upload.png">
</a>
</center>
</div>
<!-- Page 1 Footer -->
<div data-role="footer">
<h4>Footer 1</h4>
</div>
</div>
<!-- Page 2 -->
<div data-role="page" id="page2">
<!-- Page 2 Header -->
<div data-role="header">
<h1>Header 2</h1>
</div>
<!-- Page 2 Content -->
<div data-role="content">
<img style="width:100%;visibility:hidden;display:none;" id="camera_image" src="" />
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
<input id="serverUrl" type="text" value="http://kiosban.com/android/camera/upload.php" />
Status : <span id="camera_status"></span>
Skip
</div>
<!-- Page 2 Footer -->
<div data-role="footer">
<h4>Footer 2</h4>
</div>
</div>
<!-- Page 3 -->
<div data-role="page" id="page3">
<!-- Page 3 Header -->
<div data-role="header">
<h1>Header 3</h1>
</div>
<!-- Page 3 Content -->
<div data-role="content">
<div id="server_images"></div>
<h3>Server:</h3>
<b>Images on server:</b>
<div id="server_images"></div>
<input type="button" onclick="viewUploadedPictures();" value="View Uploaded Pictures" />
</div>
<!-- Page 2 Footer -->
<div data-role="footer">
<h4>Footer 2</h4>
</div>
</div>
</body>
</html>
I want to call image crop on #page2, so there is an upload button to upload the cropped image...
can anybody help me do that??
PhoneGap does not have built-in crop features. Some platforms (iPhone for sure) allows the user to crop the picture after taking it with the camera but before it would be returned to your JavaScript code if you pass the allowEdit = true parameter to getPicture. But you won't have control here from your script.
You'll have to implement the cropping feature yourself from JavaScript. It is easier then expected with the canvas tag of HTML5. You can find a pretty tutorial here.
I found the solution for this(it is too late but used for someone like me) but after taking image you need to pass the image path to the plugin(Native android) for croping.
put the following code in your image capture or pick image from gallery(in your index.html):
navigator.camera.getPicture(function(imageURI){
window.resolveLocalFileSystemURI(imageURI, function(fileEntry){
fileEntry.file(function(fileObj) {
var imagedata ="sample/new001.img";
// able to get the image location using phonegap
cropImage.createEvent(imagedata);
});
}, fail);
}, fail, { quality: 50,
destinationType: destinationType.NATIVE_URI,
sourceType: pictureSource.PHOTOLIBRARY
});
after that crop.image.js should be like (include this file name in your index.html)
var cropImage = {
createEvent: function(fileName) {
cordova.exec(
null, // success callback function
null, // error callback function
'CropImage', // mapped to our native Java class called "CropImage"
'GetImageName', // with this action name
[fileName]
);
}
}
Your java code is like
public class CropImage extends CordovaPlugin{
public final String ACTION_GET_IMAGE_NAME = "GetImageName";
Uri myUri;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
// Log.e(TAG,"Inside Version plugin.");
boolean result = false;
if(action.equals(ACTION_GET_IMAGE_NAME)) {
try {
myUri = Uri.parse(args.getString(0));
cropCapturedImage(myUri);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = true;
}
return result;
}
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// for save the image in same location with same name.
File f = new File(Environment.getExternalStorageDirectory()+"your image location here");
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
cropIntent.putExtra("output", Uri.fromFile(f));
cropIntent.putExtra("return-data", false);
//start the activity - we handle returning in onActivityResult
this.cordova.startActivityForResult((CordovaPlugin) this,cropIntent, 2);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//Log.e("final", String.valueOf(requestCode));
/*if(requestCode == 2){
//Create an instance of bundle and get the returned data
Bundle extras = intent.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
}*/
}
}
Don't forget to add this class in your CONFIG.XML and add the necessary permissions. Feel free to ask any doubts.
Related
I have an Ionic application that uses Cordova and would like to load images from the album of the device. My problem is that it is not working, although I did follow the instructions on the Cordova website. Here is my code:
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Ionic App</title>
<link href="ionic/css/ionic.css" rel="stylesheet">
<link href="css/slider-style.css" rel="stylesheet" type="text/css"/>
<link href="css/main-app.css" rel="stylesheet" type="text/css"/>
<script src="ionic/js/angular/angular.js" type="text/javascript"></script>
<script src="ionic/js/angular/angular-animate.js" type="text/javascript"></script>
<script src="ionic/js/ionic.bundle.js"></script>
<script src="ionic/js/app.js"></script>
<script src="js/myapp.js" type="text/javascript"></script>
<script src="js/LoadFromDevice.js" type="text/javascript"></script>
</head>
<body ng-app="ionicApp" animation="slide-left-right-ios7" ng-controller="PopupCtrl">
<ion-nav-bar class="nav-title-slide-ios7 bar-light transparent-nav" style="background: none; border-bottom: none">
<!-- <ion-nav-back-button class="button-icon ion-chevron-left">
</ion-nav-back-button>-->
</ion-nav-bar>
<ion-nav-view>
</ion-nav-view>
</body>
</html>
loadImage.html
<button onclick="capturePhoto();">Capture Photo</button> <br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
<script>
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
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
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// 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 in-line 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);
}
</script>
I am using the cordova-plugin-camera to achieve this.
Can you elaborate more on 'just not working'. Which step in the process does it stop working?
a. Not finding the folder?
b. Unable to select the Photo from the folder?
c. Able to select the Photo but the URI is unavailable?
d. Available URI does not render correctly?
We might be able to help you based on your answer to the above as well as details on which device, OS version, cordova version, and ionic version you are in.
There are lots of variations and issues you need to handle to have this work across devices. There are some commercial plugins that do this well like https://www.onymos.com/products/media
I'm developing a PhoneGap app with file upload and I'm using the following script which when I tap on upload picture it gives me an error Upload failed Code=3.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<style type="text/css">
div {border: 1px solid black;}
input {width: 100%;}
</style>
<script src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var options = new FileUploadOptions();
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}
</script>
</head>
<body onload="init();">
<h3>PhoneGap Camera Upload Demo</h3>
<div>
<h3>Server URL for upload.php:</h3>
<input id="serverUrl" type="text" value="http://usersamplesite.com/folder" />
</div>
<br/>
<!-- Camera -->
<div>
<h3>Camera:</h3>
<b>Status:</b> <span id="camera_status"></span><br>
<b>Image:</b> <img style="width:120px;visibility:hidden;display:none;" id="camera_image" src="" />
</div>
<!-- Actions -->
<div>
<input type="button" onclick="takePicture();" value="Take Picture" /><br/>
<input type="button" onclick="selectPicture();" value="Select Picture from Library" /><br/>
<input type="button" onclick="uploadPicture();" value="Upload Picture" />
</div>
<br/>
<!-- Server pictures -->
<div>
<h3>Server:</h3>
<b>Images on server:</b>
<div id="server_images"></div>
</div>
<!-- Actions -->
<div>
<input type="button" onclick="viewUploadedPictures();" value="View Uploaded Pictures" />
</div>
</body>
</html>
I found out here that, I should use the below script to make it work, but I don't know where to put it in the script and I need help, I'm new to PhoneGap.
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
Add true in as last param of Upload Function
upload(filePath, server, successCallback, errorCallback, options, true);
Try putting options.header inside uploadPicture() rather than putting it at start of your document.
function uploadPicture() {
......
......
if(server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.headers = {
Connection: "close"
}
options.chunkedMode = false;
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, success, failure, options, true);
}
}
I am using cordova 3.5 and want to take a picture from camera and show it on bootstrap modal. In my application there is a button that will show bootstrap modal and let you choose to take a picture from camera or gallery. After you choose you will send to camera (if you choose camrea) or gallery (if you choose gallery). It works fine until this step. But after I capture from my camera or choose image from gallery, It doesn't show any image. I don't know what to do now..
This is my code for camera and gallery, I write it on head
var pictureSource; // picture source
var destinationType; // sets the format of returned value
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
var devID;
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
//$('#header').append("pic:" + pictureSource + " dest:" + destinationType);
}
function onPhotoDataSuccess(imageData) {
$("#addPhotoModal").modal('hide');
$("#checkinModal").modal('show');
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onPhotoURISuccess(imageURI) {
$("#addPhotoModal").modal('hide');
$("#checkinModal").modal('show');
var largeImage = document.getElementById('smallImage');
largeImage.style.display = 'block';
largeImage.src = imageURI;
}
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 });
}
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message) {
$('#header').append("fail" + message);
alert('Failed because: ' + message);
}
This is my first modal to choose between camera and gallery:
<div class="modal fade rate-modal-box" id="addPhotoModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title share-modal-title" id="myModalLabel">Add Photo</h4>
</div>
<div class="modal-body photo-modal-body">
<button id="camera-btn" type="button" class="btn btn-default photo-btn">Take a Photo</button><br />
<button id="gallery-btn" type="button" class="btn btn-default photo-btn">Photo Gallery</button>
</div>
<div class="modal-footer share-modal-button">
<button type="button" class="btn btn-default share-btn" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
This is the second modal that will show the image from camera and gallery
<div class="modal fade rate-modal-box" id="checkinModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title share-modal-title" id="myModalLabel">Check In At</h4>
</div>
<div class="modal-body photo-modal-body">
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<textarea class="form-control share-text-comment" id="comment-share" name="comment" placeholder="What do you want to share"></textarea>
</div>
<div class="modal-footer share-modal-button">
<button id="save-checkin" type="button" class="btn btn-default share-btn">Submit</button>
<button type="button" class="btn btn-default share-btn" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
And here is the function to call the bootstrap modal, I write this on body
function startModalPhoto(){
$("#addPhotoModal").modal('show');
$("#camera-btn").click(function(){
capturePhoto();
});
$("#gallery-btn").click(function(){
getPhoto(pictureSource.PHOTOLIBRARY);
});
}
I hope you can help me with this.. Thanks before..
For the Gallery image, there is nowhere for the image to show:
var largeImage = document.getElementById('largeImage');
...
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
Will that display anything if you make that change?
Also, I've had much more success with FILE_URI than DATA_URL in the past when getting camera/gallery images to display in app.
When I use html5 'getUserMedia' API to access acamera on the android(4.0) phone, it comes out "front camera", but I want to open "back camera". Sample code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Html5 Mobile Carema</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(init);
function init() {
try {
window.URL = window.URL || window.webkitURL || window.msURL
|| window.oURL;
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({
video : true
}, successsCallback, errorCallback);
} catch (err) {
// Tries it with old spec of string syntax
navigator.getUserMedia('video', successsCallback, errorCallback);
}
$(":button").click(function() {
slap();
});
}
function slap() {
var video = $("#myVideo")[0];
var canvas = capture(video);
$("#result").empty();
$("#result").append(canvas);
//alert();
var imgData = canvas.toDataURL('image/png;base64,');
//var imgData = canvas.toDataURL("image/png");
var imgData = imgData.substring(22);
//blb = dataURItoBlob(imgData);
//sendMsg(blb);
}
function errorCallback(err) {
}
function successsCallback(stream) {
$("#myVideo").attr("src", window.webkitURL.createObjectURL(stream));
}
function capture(video) {
var canvas = document.createElement('canvas');
var width = video.videoWidth;
var height = video.videoHeight;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, 160, 120);
return canvas;
}
</script>
</head>
<body>
<video id="myVideo" autoplay="autoplay"></video>
<br> <input type="button" value="capture" />
<br><div id="result" style="width: 145px"></div>
<div>
<p id="resultMsg" style="color: red"></p>
<p id="decodeTime" style="color: green"></p>
</div>
</body>
</html>
I don't know how to access specific camera on android phone, anyone who knows? thanks
There is now the ability to specify a camera in the latest specification with the facingMode property: http://www.w3.org/TR/mediacapture-streams/#idl-def-VideoFacingModeEnum
This property is an optional part of the MediaStreamConstraints object that is the first argument of the getUserMedia method.
Here's a simplified example from the spec:
var supports = navigator.mediaDevices.getSupportedConstraints();
if (!supports["facingMode"]) {
// Handle lack of browser support if necessary
}
var gotten = navigator.mediaDevices.getUserMedia({
video: {
facingMode: {exact: "environment"}
}
});
The value environment means the back camera of the device. Other values are user, left and right.
Note that support for this varies depending on the browser/browser version.
See function gotSources(sourceInfos) in the code below
<!--
Based on Motion Detector Demo Created by Ákos Nikházy.
If you use this app please link this demo http://motion-detector.nikhazy-dizajn.hu/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Frame capture demo</title>
</head>
<body>
<header>
<h1>Motion Detection</h1>
<h4>with HTML5 API using .getUserMedia()</h4>
</header>
<video autoplay></video>
<hr>
<canvas id="savePhoto"></canvas>
<script>
function hasGetUserMedia() {
//returns true if supported
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
function onSuccess(stream) {
//If we can stream from camera.
var source;
//Get the stream. This goes to the video tag
if (window.URL) {
source = window.URL.createObjectURL(stream);
} else if (window.webkitURL) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream; // Opera and Firefox
}
//Set up video tag
video.autoplay = true;
video.src = source;
//We try to find motion in every X second
setInterval(function() {
motionDetector();
}, sampling);
}
function onError() {
//if we fail (not supported, no camera etc.)
alert('No stream, no win. Refresh.');
}
function saveImage(canvasToSave) {
//create image from canvas
dataUrl = canvasToSave.toDataURL();
imageFound = document.createElement('img');
imageFound.src = dataUrl;
document.body.appendChild(imageFound);
}
function motionDetector() {
ctxSave.drawImage(video, 0, 0, savePhoto.width, savePhoto.height);
}
/*After all those functions lets start setting up the program*/
//Set up elements. Should be a ini() but I don't care right now
var video = document.querySelector('video'); //the video tag
var savePhoto = document.getElementById('savePhoto'); //the possible saved image's canvas
var ctxSave = savePhoto.getContext('2d'); //the latest image from video in full size and color
var sampling = 1000; //how much time needed between samples in milliseconds
var videoSourceInfo = null;
//We need this so we can use the videoWidth and ...Height, also we setup canvas sizes here, after we have video data
video.addEventListener("loadedmetadata", function() {
console.log(video.videoWidth + ":" + video.videoHeight)
savePhoto.width = video.videoWidth;
savePhoto.height = video.videoHeight;
});
function start() { //Start the whole magic
if (hasGetUserMedia()) {
//it is working?
navigator.getUserMedia
|| (navigator.getUserMedia = navigator.mozGetUserMedia
|| navigator.webkitGetUserMedia
|| navigator.msGetUserMedia);
var videoSourceInfoId = videoSourceInfo.id;
var constraints = {
video : {
optional: [{sourceId: videoSourceInfoId}]
},
toString : function() {
return "video";
}
};
navigator.getUserMedia(constraints, onSuccess, onError);
} else {
//no support
alert('getUserMedia() is not supported in your browser. Try Chrome.');
}
}
function gotSources(sourceInfos) {
for (var i = sourceInfos.length-1 ; i >= 0; i--) { // get last camera index (supposed to back camera)
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'video') {
videoSourceInfo = sourceInfo;
console.log('SourceId: ', videoSourceInfo.id);
start();
break;
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
}
if (typeof MediaStreamTrack === 'undefined') {
alert('This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
} else {
MediaStreamTrack.getSources(gotSources); // async task
}
</script>
</body>
</html>
Hi I think this works with you
<script>
var gum = mode =>
navigator.mediaDevices.getUserMedia({video: {facingMode: {exact: mode}}})
.then(stream => (video.srcObject = stream))
.catch(e => log(e));
var stop = () => video.srcObject && video.srcObject.getTracks().forEach(t => t.stop());
var log = msg => div.innerHTML += msg + "<br>";
</script>
<button onclick="stop();gum('user')">Front</button>
<button onclick="stop();gum('environment')">Back</button>
<div id="div"></div><br>
<video id="video" height="320" autoplay></video>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
facingMode??
https://github.com/webrtcHacks/adapter/issues/820
https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode
Using Phonegap1.9.0 Camera app for android. Followed the steps as per the phonegap documentation. But when I launch the app and click on Capture phone nothing happens.
When I look into the logcat navigator.camera.getPicture is undefined
Development version specified below.
Phonegap version:1.9.0
Eclipse: 3.7.2
Android: https://dl-ssl.google.com/android/eclipse/
AVD: 4.1
Device: Samsung GT-S5830, OS- Android 2.3.6
Can someone suggest me the steps to follow and the specific version that should be used to support the Camera.
HTML Code below:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height,
initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>PhoneGap WP7</title>
<link rel="stylesheet" href="master.css" type="text/css" media="screen"
title="no title" charset="utf-8" />
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8" src="javascript.js"></script>
</head>
<body onLoad="setTimeout('delayer()', 5000)">
<h1>
VS Mag PhoneGap Photo Demo</h1>
<button onclick="capturePhoto();">Capture a Photo</button>
<br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Display from Library</button><br>
<img style="display: none; width: 200px; height: 200px;" alt="" id="capturedPhoto" src="" />
<img style="display: none; width: 200px; height: 200px;" alt="" id="selectedFromPhotoLibrary"
src="" />
</body>
</html>
Below is my JAVA SCRIPT code:
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 selectPhoto(useCamera)
{
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
if (useCamera)
{ // take picture
navigator.camera.getPicture(photoLoaded, onError, { allowEdit: true, destinationType: destinationType.FILE_URI });
}
else
{
// select from library
navigator.camera.getPicture(photoLoaded, onError, { allowEdit: true, sourceType: pictureSource.PHOTOLIBRARY, destinationType:
destinationType.FILE_URI });
}
}
//display image on the screen
function photoLoaded(imageData)
{
var temp_image=imageData;
document.getElementById("imageControl").src=temp_image;
}
// Called when a photo is successfully retrieved
function onPhotoDataSuccess(imageData) {
var capturedPhoto = document.getElementById('capturedPhoto');
capturedPhoto.style.display = 'block';
capturedPhoto.src = imageData;
navigator.notification.alert("Picture Successfully Captured!");
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI) {
var selectedFromPhotoLibrary = document.getElementById('selectedFromPhotoLibrary');
selectedFromPhotoLibrary.style.display = 'block';
selectedFromPhotoLibrary.src = imageURI;
navigator.notification.alert("Picture Imported Captured!");
}
function capturePhoto() {
// Take picture using device camera and retrieve image
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
}
// 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
});
}
// Error Handling
function onFail(message) {
alert('Failed because: ' + message);
}