Set ROS robot ip address localhost:name and set video src path - javascript

okay so i i have set robot_IP = "http://localhost:11311/"; to my localhost
and set my camera path at video.src /xtion/rgb/image_proc but the video stream still wont come out on web html . I am following what this tutorial tell me to do https://medium.com/husarion-blog/bootstrap-4-ros-creating-a-web-ui-for-your-robot-9a77a8e373f9
window.onload = function () {
// determine robot address automatically
// robot_IP = location.hostname;
// set robot address statically
robot_IP = "http://localhost:11311/";
// // Init handle for rosbridge_websocket
ros = new ROSLIB.Ros({
url: "ws://" + robot_IP + ":9090"
});
initVelocityPublisher();
// get handle for video placeholder
video = document.getElementById('video');
// Populate video source
video.src = "http://" + robot_IP + ":8080/stream?topic=/xtion/rgb/image_proc&type=mjpeg&quality=80";
video.onload = function () {
// joystick and keyboard controls will be available only when video is correctly loaded
createJoystick();
initTeleopKeyboard();
};
}

Related

camera led light not run in javascript web application

i write a code for scan passport id .. i have plustek reader (x50). i can capture image from my device in javascript (webcam.js).. but when capture image the light source not run . how can run the led light before capture image ... i need cod in javascript becouse the device in client side .. my application not mobile apps.. it web application .
// Configure a few settings and attach camera
function configure() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90,
flip_horiz: true,
});
Webcam.attach('#my_camera');
}
// A button for taking snaps
// preload shutter audio clip
var shutter = new Audio();
//shutter.autoplay = true;
shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';
function take_snapshot() {
// play sound effect
shutter.play();
// take snapshot and get image data
Webcam.snap(function (data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<img id="imageprev" src="' + data_uri + '"/>';
////////////
////////////////
var base64image = document.getElementById("imageprev").src;
var strImage = base64image.replace(/^data:image\/[a-z]+;base64,/, "");
//
// $("#<%=Image1.ClientID%>")
// .attr("src", base64image)
});
Webcam.reset();
}

HTML5 / JavaScript camera blurry, only on front facing camera, only on my app

I have built a visitor management system and have recently swapped to a surface device as the driver. The html5 webcam stream is showing as blurry / out of focus on the front facing camera. If I swap to the rear camera however it is fine. And if i use the front facing camera on another public site that uses another webcam feature, it works absolutely fine.
Here is a capture of the camera element, it looks like some form of deliberate blurring as appose to the camera just being bad...
https://ibb.co/Dzf67nC/
I have tried scanning through the code and cannot find anything that scales the camera stream at all that may cause bluring or focus changing
Below is my photo.js file that provides the stream to my visitor sign in page and also handles the capturing of screenshots.
// References to all the element we will need.
var video = document.querySelector('#camera-stream'),
image = document.querySelector('#snap'),
my_photo = document.querySelector('#my-photo'),
container = document.querySelector('.camera-container'),
//start_camera = document.querySelector('#start-camera'),
controls = document.querySelector('.controls'),
take_photo_btn = document.querySelector('#take-photo'),
delete_photo_btn = document.querySelector('#delete-photo'),
download_photo_btn = document.querySelector('#download-photo'),
imgeurl = document.querySelector('#imagesource'),
open_camera = document.querySelector('#open-camera'),
error_message = document.querySelector('#error-message');
// The getUserMedia interface is used for handling camera input.
// Some browsers need a prefix so here we're covering all the options
navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
// Mobile browsers cannot play video without user input,
// so here we're using a button to start it manually.
open_camera.addEventListener("click", function(e){
if($('#my-photo').attr('src') == '') {
e.preventDefault();
container.classList.add("visible");
// Start video playback manually.
//video.play();
//showVideo();
if(!navigator.getMedia){
displayErrorMessage("Your browser doesn't have support for the navigator.getUserMedia interface.");
}
else{
// Request the camera.
navigator.getMedia(
{
video: true
},
// Success Callback
function(stream){
// Create an object URL for the video stream and
// set it as src of our HTLM video element.
video.srcObject=stream;
// Play the video element to start the stream.
video.play();
video.onplay = function() {
showVideo();
};
},
// Error Callback
function(err){
displayErrorMessage("There was an error with accessing the camera stream: " + err.name, err);
}
);
}
}
});
open_camera.click();
take_photo_btn.addEventListener("click", function(e){
e.preventDefault();
var count=4;
var counter=setInterval(timer, 500); //1000 will run it every 1 second
$('.countdown-container').addClass('visible');
function timer(){
count=count-1;
if (count <= 0)
{
$('.countdown-number').html('<i class="far fa-smile"></i>');
clearInterval(counter);
//counter ended, do something here
return;
}
$('.countdown-number').text(count);
//Do code for showing the number of seconds here
}
setTimeout(function(){
$('.countdown-container').removeClass('visible');
$('.countdown-number').text('Get Ready');
},2500);
setTimeout(function(){
video.pause(snap);
var snap = takeSnapshot();
// Show image.
image.setAttribute('src', snap);
imgeurl.value = snap;
image.classList.add("visible");
//tumbnail image
my_photo.setAttribute('src', snap);
my_photo.value = snap;
// Enable delete and save buttons
delete_photo_btn.classList.remove("disabled");
download_photo_btn.classList.remove("disabled");
take_photo_btn.classList.add("disabled");
},3000);
// Set the href attribute of the download button to the snap url.
// Pause video playback of stream.
});
delete_photo_btn.addEventListener("click", function(e){
e.preventDefault();
// Hide image.
image.setAttribute('src', "");
image.classList.remove("visible");
my_photo.setAttribute('src', "");
// Disable delete and save buttons
delete_photo_btn.classList.add("disabled");
download_photo_btn.classList.add("disabled");
take_photo_btn.classList.remove("disabled");
// Resume playback of stream.
video.play();
});
function showVideo(){
// Display the video stream and the controls.
//hideUI();
video.classList.add("visible");
controls.classList.add("visible");
}
function takeSnapshot(){
// Here we're using a trick that involves a hidden canvas element.
var hidden_canvas = document.querySelector('canvas'),
context = hidden_canvas.getContext('2d');
var width = video.videoWidth,
height = video.videoHeight;
if (width && height) {
// Setup a canvas with the same dimensions as the video.
hidden_canvas.width = width;
hidden_canvas.height = height;
// Make a copy of the current frame in the video on the canvas.
context.drawImage(video, 0, 0, width, height);
// Turn the canvas image into a dataURL that can be used as a src for our photo.
return hidden_canvas.toDataURL('image/png');
}
}
download_photo_btn.addEventListener("click", function(e){
e.preventDefault();
container.classList.remove("visible");
my_photo.classList.add("visible");
});
function displayErrorMessage(error_msg, error){
error = error || "";
if(error){
console.log(error);
}
error_message.innerText = error_msg;
hideUI();
error_message.classList.add("visible");
}
function hideUI(){
// Helper function for clearing the app UI.
controls.classList.remove("visible");
//start_camera.classList.remove("visible");
video.classList.remove("visible");
snap.classList.remove("visible");
error_message.classList.remove("visible");
}
The camera should be a lot crisper than it is. No errors or anything in the console.

Saving a image which is captured by a camera on local machine on a folder

I am using HTML5 inputs to take a picture from camera using below line,
<input id="cameraInput" type="file" accept="image/*;capture=camera"></input>
and getting used image in blob:, using following javascript,
var mobileCameraImage = function() {
var that = this
;
$("#cameraInput").on("change", that.sendMobileImage);
if (!("url" in window) && ("webkitURL" in window)) {
window.URL = window.webkitURL;
}
});
var sendMobileImage = function( event ) {
var that = this;
if (event.target.files.length == 1 && event.target.files[0].type.indexOf("image/") == 0) {
var capturedImage = URL.createObjectURL(event.target.files[0])
;
alert( capturedImage );
}
});
Here, I am getting proper image url but the problem i am facing is to send this image url to the server, After reading blogs i found i can not send Blob: url to the server due to its local instance. Does anyone can help to save the clicked image on local machine on a folder or any where, or to help how i can send this image url to the server.
Thanks in advance.
You may need to submit your form every time via Ajax or you may upload the image data manually. In order to do that, you may draw the image unto a canvas, then obtain the canvas data.
// create an image to receive the data
var img = $('<img>');
// create a canvas to receive the image URL
var canvas = $('<canvas>');
var ctx = canvas[0].getContext("2d");
$("#cameraInput").on("change", function () {
var capturedImage = URL.createObjectURL(this.files[0]);
img.attr('src', capturedImage);
ctx.drawImage(img);
var imageData = canvas[0].toDataURL("image/png");
// do something with the image data
});
Or use a FileReader
// only need to create this once
var reader = new FileReader();
reader.onload = function () {
var imageData = reader.result;
// do something with the image data
};
$("#cameraInput").on("change", function () {
reader.readAsDataURL(this.files[0]);
});
Then you can upload that data to the server.

Create thumbnail from video file via file input

I am attempting to create a thumbnail preview from a video file (mp4,3gp) from a form input type='file'. Many have said that this can be done server side only. I find this hard to believe since I just recently came across this Fiddle using HTML5 Canvas and Javascript.
Thumbnail Fiddle
The only problem is this requires the video to be present and the user to click play before they click a button to capture the thumbnail. I am wondering if there is a way to get the same results without the player being present and user clicking the button. For example: User click on file upload and selects video file and then thumbnail is generated. Any help/thoughts are welcome!
Canvas.drawImage must be based on html content.
source
here is a simplier jsfiddle
//and code
function capture(){
var canvas = document.getElementById('canvas');
var video = document.getElementById('video');
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
}
The advantage of this solution is that you can select the thumbnail you want based on the time of the video.
Recently needed this so I wrote a function, to take in a video file and a desired timestamp, and return an image blob at that time of the video.
Sample Usage:
try {
// get the frame at 1.5 seconds of the video file
const cover = await getVideoCover(file, 1.5);
// print out the result image blob
console.log(cover);
} catch (ex) {
console.log("ERROR: ", ex);
}
Function:
function getVideoCover(file, seekTo = 0.0) {
console.log("getting video cover for file: ", file);
return new Promise((resolve, reject) => {
// load the file to a video player
const videoPlayer = document.createElement('video');
videoPlayer.setAttribute('src', URL.createObjectURL(file));
videoPlayer.load();
videoPlayer.addEventListener('error', (ex) => {
reject("error when loading video file", ex);
});
// load metadata of the video to get video duration and dimensions
videoPlayer.addEventListener('loadedmetadata', () => {
// seek to user defined timestamp (in seconds) if possible
if (videoPlayer.duration < seekTo) {
reject("video is too short.");
return;
}
// delay seeking or else 'seeked' event won't fire on Safari
setTimeout(() => {
videoPlayer.currentTime = seekTo;
}, 200);
// extract video thumbnail once seeking is complete
videoPlayer.addEventListener('seeked', () => {
console.log('video is now paused at %ss.', seekTo);
// define a canvas to have the same dimension as the video
const canvas = document.createElement("canvas");
canvas.width = videoPlayer.videoWidth;
canvas.height = videoPlayer.videoHeight;
// draw the video frame to canvas
const ctx = canvas.getContext("2d");
ctx.drawImage(videoPlayer, 0, 0, canvas.width, canvas.height);
// return the canvas image as a blob
ctx.canvas.toBlob(
blob => {
resolve(blob);
},
"image/jpeg",
0.75 /* quality */
);
});
});
});
}
Recently needed this and did quite some testing and boiling it down to the bare minimum, see https://codepen.io/aertmann/pen/mAVaPx
There are some limitations where it works, but fairly good browser support currently: Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+).
video.preload = 'metadata';
video.src = url;
// Load video in Safari / IE11
video.muted = true;
video.playsInline = true;
video.play();
You can use this function that I've written. You just need to pass the video file to it as an argument. It will return the dataURL of the thumbnail(i.e image preview) of that video. You can modify the return type according to your need.
const generateVideoThumbnail = (file: File) => {
return new Promise((resolve) => {
const canvas = document.createElement("canvas");
const video = document.createElement("video");
// this is important
video.autoplay = true;
video.muted = true;
video.src = URL.createObjectURL(file);
video.onloadeddata = () => {
let ctx = canvas.getContext("2d");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
video.pause();
return resolve(canvas.toDataURL("image/png"));
};
});
};
Please keep in mind that this is a async function. So make sure to use it accordingly.
For instance:
const handleFileUpload = async (e) => {
const thumbnail = await generateVideoThumbnail(e.target.files[0]);
console.log(thumbnail)
}
The easiest way to display a thumbnail is using the <video> tag itself.
<video src="http://www.w3schools.com/html/mov_bbb.mp4"></video>
Use #t in the URL, if you want the thumbnail of x seconds.
E.g.:
<video src="http://www.w3schools.com/html/mov_bbb.mp4#t=5"></video>
Make sure that it does not include any attributes like autoplay or controls and it should not have a source tag as a child element.
With a little bit of JavaScript, you may also be able to play the video, when the thumbnail has been clicked.
document.querySelector('video').addEventListener('click', (e) => {
if (!e.target.controls) { // Proceed, if there are no controls
e.target.src = e.target.src.replace(/#t=\d+/g, ''); // Remove the time, which is set in the URL
e.target.play(); // Play the video
e.target.controls = true; // Enable controls
}
});
<video src="http://www.w3schools.com/html/mov_bbb.mp4#t=5"></video>
With jQuery Lib you can use my code here. $video is a Video element.This function will return a string
function createPoster($video) {
//here you can set anytime you want
$video.currentTime = 5;
var canvas = document.createElement("canvas");
canvas.width = 350;
canvas.height = 200;
canvas.getContext("2d").drawImage($video, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/jpeg");;
}
Example usage:
$video.setAttribute("poster", createPoster($video));
I recently stumbled on the same issue and here is how I got around it.
firstly it will be easier if you have the video as an HTML element, so you either have it in the HTML like this
<video src="http://www.w3schools.com/html/mov_bbb.mp4"></video>
or you take from the input and create an HTML element with it.
The trick is to set the start time in the video tag to the part you want to seek and have as your thumbnail, you can do this by adding #t=1.5 to the end of the video source.
<video src="http://www.w3schools.com/html/mov_bbb.mp4#t=1.5"></video>
where 1.5 is the time you want to seek and get a thumbnail of.
This, however, makes the video start playing from that section of the video so to avoid that we add an event listener on the video's play button(s) and have the video start from the beginning by setting video.currentTime = 0
const video = document.querySelector('video');
video.addEventListener('click', (e)=> {
video.currentTime = 0 ;
video.play();
})

HTML5 Canvas Drag out from browser to desktop

I'm trying to create a little image manipulation web app as a project. I'm trying to implement a Drag canvas image out of the browser to the desktop. I have done some digging and found
http://www.thecssninja.com/javascript/gmail-dragout and http://jsfiddle.net/bgrins/xgdSC/ (courtesy of TheCssNinja & Brian Grinstead)
function dragoutImages() {
if (!document.addEventListener) {
return;
}
document.addEventListener("dragstart", function(e) {
var element = e.target;
var src;
if (element.tagName === "IMG" && element.src.indexOf("data:") === 0) {
src = element.src;
}
if (element.tagName === "CANVAS") {
try {
src = element.toDataURL();
}
catch(e) { }
}
if (src) {
var name = element.getAttribute("alt") || "download";
var mime = src.split(";")[0].split("data:")[1];
var ext = mime.split("/")[1] || "png";
var download = mime + ":" + name + "." + ext + ":" + src;
e.dataTransfer.setData("DownloadURL", download);
}
}, false);
}
function drawCanvas(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var lingrad = ctx.createLinearGradient(0,0,0,150);
lingrad.addColorStop(0, '#000');
lingrad.addColorStop(0.5, '#669');
lingrad.addColorStop(1, '#fff');
ctx.fillStyle = lingrad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
var img = new Image();
img.src = canvas.toDataURL("image/png");
img.alt = 'downloaded-from-image';
$(img).appendTo("body");
}
dragoutImages();
drawCanvas();
This works for files which are elements of the HTML but I am unable to grab the canvas image and download it using the theory. Has anyone implemented such a feature?
I have used the canvas.toDataURL to get the image data, if I do an alert I see the encoded image data my canvas drag begins but when outside the browser the icon changes back to the stop symbol.
Looking for approaches and ideas on how to implement this.
This is what I've managed to implement and works pretty well,
function download(e){
downloadImageData = eCanv.getImageData(750 - (scaledWidth / 2), 250 - (scaledHeight / 2), scaledWidth, scaledHeight);
dlcanvas = document.createElement('canvas');
dlcanvas.setAttribute('width',scaledWidth);
dlcanvas.setAttribute('height',scaledHeight);
dlcontext = dlcanvas.getContext("2d");
dlcontext.putImageData(downloadImageData, 0,0);
url = dlcanvas.toDataURL('image/jpg');
//name = document.getElementById("filename").value;
var mime = url.split(";")[0].split("data:")[1];
var name = mime.split("/")[0];
var ext = mime.split("/")[1] || "jpg";
var download = mime + ":" + name + "." + ext + ":" + url;
e.dataTransfer.setData("DownloadURL", download);
}
Adapted code from cssninja and Brian Grinstead.
No.
For security reasons, Javascript cannot write to the local file system.
Javascript can read from the local file system with the filereader: http://www.html5rocks.com/en/tutorials/file/dndfiles/
It can even write to a sandboxed browser file (localstorage): http://www.w3schools.com/html/html5_webstorage.asp
You could even bounce it off your server and then ask the user if they want to download the image off the server.
For local web based applications you can use or write a local webserver or service and or utilzize for example php to add the functionality to interact with the local filesystem from javascript. Seems this is forgotten that it is not forbidden to install a webserver on the same machine like the browser :)

Categories