android - Selected photo from gallery rotates in landscape in phonegap - javascript

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

Related

How to fix this error : NotReadableError: Could not start video source

I am trying to implement video recording but getting this error. i have 2 buttons called Front Camera ,Back Camera. On click i am calling below method. first it displays the camera correctly but while switching camera it gives me the error. Please help how to fix the problem ?
function StartVideoCamera(obj) {
var id = $(obj).attr('id');
var camNode = $(obj).attr('cammode');
if (camNode != 'user') {
camNode = eval('{ exact: "environment" }')
}
var video = document.querySelector('#video' + id);
var constraints = { audio: true, video: { width: videoHeight, height: videoWidth, facingMode: camNode
} };
navigator.mediaDevices.getUserMedia(constraints)
.then(function (mediaStream) {
window.stream = null;
video.srcObject = null;
recordButton.disabled = false;
window.stream = mediaStream;
video.srcObject = mediaStream;
video.onloadedmetadata = function (e) {
video.play();
};
})
.catch(function (err) {
alert(err.name + ": " + err.message)
console.log(err.name + ": " + err.message);
});
}
You need to stop the previous mediaStreamObj before calling getUserMedia again.
This happens when your other(front/back) is already in use. You need to release the camera first.
stream.getTracks()
.forEach(track => track.stop());
Here stream is what you got from getUserMedia
This stops all the devices (you can check that the camera light goes off on the desktop) and (on mobile devices).

Sweetalert2 modal loads briefly before image appears in modal

I'm using Sweetalert2 to display a modal that has an image inside. Although it works fine, the modal without the image shows for a split second before the image appears. How can I wait until the image fully loads. Here's what I've tried that doesn't work: (loadPage is called when the page loads.)
function loadPage() {
var img = new Image();
img.onload = function () { setTimeout(function () { getToast(); }, 5000); }
img.src = "Images/Save.png";
}
function getToast() {
const Toast = Swal.mixin({
toast: false,
showConfirmButton: true,
confirmButtonText: 'close',
timer: 6000,
imageUrl: 'Images/Save.png',
timerProgressBar: true,
title: 'My message.',
})
Toast.fire({
})
}
The way you're doing it should just work without any flicker. The image is downloaded, cached and on the subsequent requests it should be served from cache. I created a fiddle and could not reconstruct your described issue.
Although I created an alternative approach saving the downloaded image as an dataURI and passing it to your SweetAlert instance. This way you can prevent accidentally downloading the image multiple times.
function loadPage() {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL('canvas');
setTimeout(function () { getToast(dataURL); }, 1000);
canvas = null;
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png';
}
function getToast(dataURL) {
const Toast = Swal.mixin({
toast: false,
showConfirmButton: true,
confirmButtonText: 'close',
timer: 6000,
imageUrl: dataURL,
timerProgressBar: true,
title: 'My message.',
})
Toast.fire({
})
}
loadPage()
Also see the attached fiddle for a working example: https://jsfiddle.net/4sza8u2m/

How to take picture and set it as background using phonegap

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

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

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