How to take picture and set it as background using phonegap - javascript

I am using phonegap to build my app, In the app i am building i have a camera which turns on when i open the app and i see camera controls. once i capture the picture the captured picture should get set as my app background image. how can i do that?
here's what i have tried:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
encodingType: Camera.EncodingType.JPEG,
saveToPhotoAlbum: true,
showOverlay: false
});
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
alert(image.src);
document.body.style.backgroundImage = "url(image.src)";
}
function onFail(message) {
/*alert("you are closing the camera")*/
}
}

Your onSuccess function should look like this
function onSuccess(imageData) {
var image = "data:image/jpeg;base64," + imageData;
document.body.style.backgroundImage = "url(" + image + ")";
}

Related

Vimeo videos do not load

I would like to use integrated Vimeo videos on a page and have them start playing as soon as the page is loaded and when the first video has finished, the second one starts. In my code I have an array of video ids but my problem is the video does not load.
<div id="headervideo"></div>
<script src="https://player.vimeo.com/api/player.js"></script>
<script>
//====================
document.addEventListener("DOMContentLoaded", function(event) {
var videos = ['240512614', '227735391']; // videos ids
var options = {
width: 640,
loop: true
};
var player = new Vimeo.Player('headervideo', options);
playMovie(player, videos)
})//end function
//====================
var playMovie = function(player, videos) {
if(!videos.length){
return false;
}
var video = videos.shift();
alert (video)
player.loadVideo(videos).then(function(id) {
alert("the video successfully loaded ")
player.getEnded().then(function(ended) {
playMovie(player, videos)
}).catch(function(error) {
console.warn(error)
});
}).catch(function(error) {
console.warn(error);
});
}//end function
//====================
</script>
Your first issue lies in
new Vimeo.Player('headervideo', options);
You cannot create a Vimeo.Player without specifying a video in the options object (or as an html attribute on an associated element).
So, specifying either:
var video = videos.shift();
var options = {
width: 640,
loop: true,
id: video
}
or:
var options = {
width: 640,
loop: true,
id: videos[0]
}
Will let you load the video.
But this will raise your second issue, that playMovie will not wait for your currently playing video to finish, but rather swap the video out immediately. getEnded() is not a synchronously blocking function.
What you want to do is instead listen on the ended event. And also turn of the loop: true as this will disable the ended event
document.addEventListener("DOMContentLoaded", function(event) {
window.videos = ['240512614', '227735391']; // videos ids
var video = videos.shift();
var options = {
width: 640,
loop: false,
id: video
};
window.player = new Vimeo.Player('headervideo', options);
window.player.on('ended', playNext);
window.player.play();
})//end function
//====================
var playNext= function() {
alert('foo');
if(!window.videos.length){
return false;
}
var video = window.videos.shift();
alert (video);
player.loadVideo(video).then(function(id) {
alert("the video "+id+" successfully loaded ");
player.play();
}).catch(function(error) {
console.warn(error)
});
}//end function

Video stream to canvas to image using JavaScript for Project Oxford

I've been able to use Project Oxford, specifically the Emotions API by manually asking a user to upload pictures. However, I'm now looking to do this using a video stream (the webpage shows a live video stream from their webcam and the user can take a snapshot of the stream and then choose to have the emotions API run on that image, which will then run the API and show the scores in a dialogue window - this is the part which I am currently stuck with).
Below I've written the HTML and JavaScript code which sets up the video stream on the webpage and then allows the user to take a snapshot, which then converts the canvas to an image.
<video id="video" width="640" height="480" autoplay></video>
<button id="snap">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<img id="file" src = "" alt="Emotions">
<!--input type="file" id="file" name="filename"-->
<button id="btn">Click here</button>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
var dataURL = document.getElementById("canvas");
if (dataURL.getContext){
var ctx = dataURL.getContext("2d");
var link = document.createElement('a');
link.download = "test.png";
var myImage = link.href = dataURL.toDataURL("image/png").replace("image/png", "image/octet-stream");
link.click();
}
var imageElement = document.getElementById("file");
imageElement.src = myImage;
//document.getElementById("file").src = dataURL;
$('#btn').click(function () {
//var file = document.getElementById('file').files[0];
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj) {
// Request headers
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", "my-key");
},
type: "POST",
data: imageElement,
processData: false
})
.done(function(data) {
JSON.stringify(data);
alert(JSON.stringify(data));
})
.fail(function(error) {
//alert(error.getAllResponseHeaders());
alert("Error");
});
});
});
}, false);
</script>
I'm not able to get the API running on the image after it's been converted as a canvas. After reading around, I believe this has something to do with the file extension that's given to the image after it's been converted as a canvas (there is none), as the API only allows for image file types. I believe this might be where the problem lies and any help would be very much appreciated. Many thanks!
This is the code I'm using to upload the picture to a backend API, which then use the .NET SDK after adding some business logic.
It is not the exact same scenario but the Javascript code might help you:
var url = 'Home/upload';
var data = new FormData();
data.append('file', imgData);
var imgData = canvas.msToBlob('image/jpeg');
$.ajax({
type: 'POST',
url: url,
data: data,
processData: false,
contentType: false
})
.done(function (response) {
loading.style.display = "none";
if (response.error != "") {
result.innerText = response.error;
}
else {
result.innerHTML = response.result;
}
})
.fail(function (response) {
alert('Error : ' + response.error);
})
.complete(function (response) {
restartButton.style.display = 'inline-block';
});
The following thread helped me: Pass Blob through ajax to generate a file

android - Selected photo from gallery rotates in landscape in phonegap

I'm using the phonegap file upload to upload files to a server. When i select a portrait photo from the gallery it rotates to landscape
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,correctOrientation : true, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
there is a "correctOrientation" parameter for getPicture (http://docs.phonegap.com/en/edge/cordova_camera_camera.md.html) try setting it to false (or true :D)
Hope this helps

Camera and PictureSourceType not defined Phonegap

I am trying to get the camera working from a button but am getting errors on the commented lines below. I am using the documentation provided by Phonegap/Cordova (v2.1). Any help appreciated.
var pictureSource = navigator.Camera.PictureSourceType.CAMERA; // Cannot read PictureSourceType of undef
var destinationType = navigator.camera.DestinationType.FILE_URI;
function onPhotoURISuccess(imageURI) {
var placeImage = document.getElementById('placeImage');
placeImage.src = imageURI;
placeImage.style.display = 'block';
console.log(imageURI);
}
function getPhoto() {
navigator.Camera.getPicture(onPhotoURISuccess, onFail, { //I am getting an error for this line saying camera is not defined?
quality: 50,
destinationType: camera.destinationType.FILE_URI,
sourceType: pictureSource
});
}
function onFail(message) {
alert('Failed because: ' + message);
}
Make sure you've got "deviceready" event first. For your call to getPicture() do this:
navigator.Camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: pictureSource
});
I am also working on this. If you are talking about Android, you need to test on a real device. No matter you test on browser or simulator in Eclipse, it will give you Camera not defined error. I guess it is because hardware problem.

Access images in SD card

var pictureSource; // picture source
var destinationType; // sets the format of returned value
var photoid=window.localStorage.getItem("photoid");
var photoData=null;
// 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;
}
// A button will call this function
//
function getPhoto(source) {
alert("Entered sd card");
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onPhotoDataSuccess(imageData) {
console.log(imageData);
// Get image handle
var smallImage = document.getElementById('photos');
// 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(imageData);
photoData = imageData;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("/sdcard/external_sd/"+photoid+".jpg", null, gotFileEntry, fail);
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
alert("write success");
};
writer.write(photoData);
}
function fail(error) {
alert(error.code);
}
/* function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
console.log(imageURI);
alert("photo captured");
uploadPhoto(imageURI);
} */
/* function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType,
sourceType: source });
} */
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
I have used the above code to access data in the sd card. But now what i need to do is, get the path of the images present there and put it in a diff object that can access the path and display those images. I have no clue on how to go about that.
Any help is appreciated.
What you can do is write a phonegap plugin for the platform you are developing for. I'll assume it's android. Writing android plugins.
When you call the Phonegap.exec to call the plugin, the plugin, gets the sd card path through
Environment.getExternalStorageDirectory().getAbsolutePath()
and then does a basic search to get all the .jpg and .png files and return a json of all the paths of the files.

Categories