broken image after writing Base64 image using FileWriter - html

I want to add some text over image taken from device camera using cordova camera plugin.
For that i used canvas and draw text over the image and saved using FileWriter.writer() method, but while i checked image in gallery, image is shown as broken and, in proprties resolution is -1x-1.
while i debug, before calling write() i am able see base64 image and when i clicked,image is opened in new tab.
Please find my code and please provide your comments.
var gImageURI = '';
var gFileSystem = {};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, errorHandler);
function getPhoto(source, type) {
navigator.camera.getPicture(function (imageURI) { onPhotoURISuccess(imageURI, type) }, onFail, {
quality: 35,
destinationType: navigator.camera.DestinationType.FILE_URI,
saveToPhotoAlbum: false,
sourceType: source,
allowEdit: false,
targetWidth: 600,
targetHeight: 800
});
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI, type) {
if(type=="camera")
canvasimage(imageURI);
}
// Called if something bad happens.
function onFail(message) {
console.log('Failed because: ' + message);
}
// sets the filesystem to the global var gFileSystem
function gotFS(fileSystem) {
gFileSystem = fileSystem;
}
// send the full URI of the moved image to the updateImageSrc() method which does some DOM manipulation
function movedImageSuccess(fileEntry, type) {
debugger;
updateImageSrc(fileEntry.fullPath, type);
}
// simple error handler
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = e.code;
break;
};
console.log('Error: ' + msg);
}
function btnCameraClick() {
$("#divAttachments").show();
$("#divLandmarks").hide();
getPhoto(navigator.camera.PictureSourceType.CAMERA, 'camera');
}
function updateImageSrc(filepath, type) {
try {
var filenamewithextensn = filepath.substring(filepath.lastIndexOf('/') + 1);
var strfilename = filenamewithextensn.split('.');
var filename = strfilename[0];
var tag = filepath.substring(filepath.lastIndexOf('/') + 1);
// alert('File Path after moving : ' + filepath);
// alert('tag :' + tag);
var fullpath = gFileSystem.root.toURL() + tag;
// alert('full path to dataabase '+fullpath);
var query = "";
if (type == "camera") {
//query= insert query
}
}
catch (err) {
ErrorMessageDB("something");
}
}
function canvasimage(src) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var imgdata = new Image;
imgdata.onload = function () {
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0, 0);
ctx.font = "11pt Verdana";
ctx.fillStyle = "black";
ctx.fillText("19-11-2014", 22, 42);
ctx.fillStyle = "white";
ctx.fillText("19-11-2014", 20, 40);
var dataURL = canvas.toDataURL();
//alert(dataURL);
//dataURL=dataURL.substring(dataURL.indexOf("base64\,") + 7);
gotfilesystem(dataURL);
}
imgdata.src = src;
//var index = dataURL.indexOf(',');
//return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
// return dataURL;
}
function gotfilesystem(dataURL) {
var d = new Date();
var s = d.getDate().toString() + d.getMonth().toString() + d.getMinutes().toString() + d.getSeconds().toString()
var fname="thumbnail_" + s + ".png";
gFileSystem.root.getFile(fname, { create: true, exclusive: false },
function(entry) {
gotfileentrysuccess(entry, dataURL);
}, function() {
});
}
function gotfileentrysuccess(entry, dataURL) {
entry.createWriter( function(fileWriter) {gotFileWriter(fileWriter,dataURL,entry)});
}
function gotFileWriter(writer, dataURL,entry) {
writer.onwriteend = function(evt) {
movedImageSuccess(entry, 'camera');
};
writer.write(dataURL);
}

You need to create a Blob using your base64 string then pass the Blob to the FileWriter.writer() method.
There is a nice example of how to do this here:
Convert Data URI to File then append to FormData

Related

fabricJS: Scale canvas view

I have converted a pdf to image format using PDF.JS and rendered that to the canvas. While that process the rendered pdf image is showing blurred in the canvas.
I have no idea how to scale the image to some viewable format rather than being so blurred.
Image of the pdf in canvas:
Here in the image you can clearly see that the rendered image is not in readable format!
Here is the fiddle link: https://jsfiddle.net/kjxes63f/
var fabricCanvas;
fabricCanvas = new fabric.Canvas('firtcanvas');
document.querySelector("#pdf-upload").addEventListener("change", function (e) {
var file = e.target.files[0]
console.log("pdf evente");
console.log(e);
if (file.type != "application/pdf") {
console.error(file.name, "is not a pdf file.")
return
}
var fileReader = new FileReader();
fileReader.onload = function () {
var typedarray = new Uint8Array(this.result);
console.log("typedarray");
console.log(typedarray);
console.log("this.result");
console.log(this.result);
PDFJS.getDocument(typedarray).then(function (pdf) {
// you can now use *pdf* here
console.log("the pdf has ", pdf.numPages, "page(s).")
pdf.getPage(pdf.numPages).then(function (page) {
// you can now use *page* here
var viewport = page.getViewport(2.0);
var fabricCanvas = document.querySelector("#firtcanvas")
fabricCanvas.height = viewport.height;
fabricCanvas.width = viewport.width;
page.render({
canvasContext: fabricCanvas.getContext('2d'),
viewport: viewport
}).then(function () {
bg = fabricCanvas.toDataURL("image/png");
fabric.Image.fromURL(bg, function (img) {
img.scaleToHeight(800);
img.scaleToWidth(600);
console.log("img");
console.log(img);
console.log(bg);
var imgCanvas = img.set({ left: 0, top: 0, width: 150, height: 150 });
fabricCanvas.add(imgCanvas);
});
});
});
});
};
fileReader.readAsArrayBuffer(file);
});
Construction drawings are often wide-format and hard to read onscreen without zoom. As a work-around I'd suggest adding a zoom function to your canvas like below.
var canvas = new fabric.Canvas('pdfcanvas');
canvas.selection = false;
canvas.setHeight(450);
canvas.setWidth(636);
//zoom function
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
var pointer = canvas.getPointer(opt.e);
var zoom = canvas.getZoom();
zoom = zoom - delta / 200;
if (zoom > 10) zoom = 10;
if (zoom < 1) {
zoom = 1;
canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
}
canvas.zoomToPoint({
'x': opt.e.offsetX,
'y': opt.e.offsetY
}, zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
});
//pdf load
document.querySelector('#pdf-upload').addEventListener('change', function(e) {
var pageEl = document.getElementById('page-container');
var file = e.target.files[0];
if (file.type == 'application/pdf') {
var fileReader = new FileReader();
fileReader.onload = function() {
var typedarray = new Uint8Array(this.result);
PDFJS.getDocument(typedarray).then(function(pdf) {
//console.log('the pdf has ', pdf.numPages, 'page(s).');
pdf.getPage(pdf.numPages).then(function(pageEl) {
var viewport = pageEl.getViewport(2.0);
var canvasEl = document.querySelector('canvas');
canvasEl.height = viewport.height;
canvasEl.width = viewport.width;
pageEl.render({
'canvasContext': canvasEl.getContext('2d'),
'viewport': viewport
}).then(function() {
var bg = canvasEl.toDataURL('image/png');
fabric.Image.fromURL(bg, function(img) {
canvas.setBackgroundImage(img);
});
});
});
});
};
fileReader.readAsArrayBuffer(file);
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.349/pdf.min.js"></script>
<input id="pdf-upload" type="file">
<div id="page-container">
<canvas id="pdfcanvas"></canvas>
</div>

why i can't get full image size from convertToDataURLviaCanvas method in ionic 3?

I want original image size in offline mode also as shown in online mode in image 2.
My problem is that when i gone in app without internet connection, i loss full quality and size of images, because of i am using convertToDataURLviaCanvas().
so, please give here solution as soon as possible.
My code is:
I am using this function to convert all images:
convertToDataURLviaCanvas(url, outputFormat) {
return new Promise((resolve, reject) =>
{
let img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
let canvas = <HTMLCanvasElement>document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
dataURL;
canvas.height = 1000;
canvas.width = 1000;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL();
//callback(dataURL);
canvas = null;
resolve(dataURL);
};
img.src = url;
});
}
getTravelAdviceData() {
if(this.restProvider.getNetworkType() == 'none') {
// this.onlineGrid = false;
// this.offlineGrid = true;
this.storage.get('companyLogoOffline').then((data) => {
// Do something with latitude value
// console.log("offline data", data);
this.getcompanyLogo = data;
});
this.storage.get('travelTips64Image').then((data) => {
// Do something with latitude value
// console.log("offline data", data);
this.adviceArray = data;
// console.log("offline this.adviceArray", this.adviceArray);
});
} else {
// this.offlineGrid = false;
// this.onlineGrid = true;
this.restProvider.getTravelAdvice()
.then(data => {
let serviceData : any = data['consejosviaje'];
// this.adviceArray = serviceData;
let base64Image;
for (let i in serviceData) {
this.imagen = serviceData[i].imagen;
this.convertToDataURLviaCanvas(this.imagen, "image/jpeg").then(base64 => {
base64Image = base64;
this.texto = serviceData[i].texto;
this.adviceArrays64.push({'texto': this.texto, 'imagen': base64Image});
this.storage.set("travelTips64Image", this.adviceArrays64);
this.adviceArray = this.adviceArrays64;
});
}
});
}
}

Decode/Encode .swf file

I have this .swf file: http://www.mediafire.com/download/hrr3c6c188jsgvd/upload.swf
I need to change something in this file, so I have this website http://www.showmycode.com/ decode the file and got those code:
if (!hasOwnProperty("_load05626E90")) {
_load05626E90 = true;
telltarget ("..") {
var copyright = function () {
telltarget ("..") {
geturl("http://www.google.com/search?q=PHP+Script+c-Image+Uploader+3.0", "_blank");
}
};
}
}
else {
// unexpected jump
}
var author = function () {
telltarget ("..") {
geturl("http://chiplove.biz", "_blank");
}
};
// unexpected jump
// unexpected jump
var uploadItem = function (num) {
telltarget ("..") {
var item = flash.net.FileReference(list[num]);
item.addlistener(listener2);
item.upload((((((((((("upload.php?watermark=" + watermark) + "&logo=") + logo) + "&resize=") + resize) + "&server=") + server) + "&q=") + q)+ "&account=") + account)+ "&password=") + password);
}
};
// unexpected jump
// unexpected jump
var FileChooser = function () {
telltarget ("..") {
var fileRef = new flash.net.FileReferenceList();
fileRef.addlistener(listener);
fileRef.browse(allTypes);
}
};
// unexpected jump
// unexpected jump
};
stop();
//---------------------------------------------------------------------- //Frame 1 //----------------------------------------------------------------------
this.menu = new contextmenu();
this.menu.hidebuiltinitems();
this.menu.customitems.push(new contextmenuitem("PHP Script - c-Image Uploader 3.0", copyright));
this.menu.customitems.push(new contextmenuitem("Powered by chiplove.9xpro", author));
//---------------------------------------------------------------------- //Symbol 3 Button //----------------------------------------------------------------------
on (press) {
var listener = new object();
var listener2 = new object();
var itemnum = 0;
var numfiles = 0;
delete _global.__resolve;
_global.__resolve = _global.__debugResolve;
if (list == undefined) {
var list = null;
}
var allTypes = new array();
var imageTypes = new object();
imageTypes.description = "Images (*.jpg; *.jpeg; *.jpe; *.gif; *.png;)";
imageTypes.extension = "*.jpg; *.JPG; *.jpeg; *.jpe; *.gif; *.png;";
allTypes.push(imageTypes);
listener.onselect = function (fileRefList) {
list = fileRefList.fileList; numfiles = list.length;
uploadItem(itemnum);
};
listener2.onOpen = function (file) { };
listener2.onProgress = function (file, bytesloaded, bytestotal) {
flash.external.ExternalInterface.call("loading");
};
listener2.onComplete = function (file) { };
listener2.onUploadCompleteData = function (file, data) {
var loadvars = new loadvars();
loadvars.decode(data);
flash.external.ExternalInterface.call("displaypic", file.name, loadvars.image);
itemnum = itemnum + 1;
if (itemnum < numfiles) {
uploadItem(itemnum);
}
else {
flash.external.ExternalInterface.call("responseStatus", "Done!");
}
};
flash.external.ExternalInterface.addCallBack("FileChooser", this, FileChooser);
flash.external.ExternalInterface.call("clearlist");
FileChooser();
}
I think this is Action Script code, so after make some little change I get flash builder to recompile it, however, flash builder show a lot of red underline (syntax error) in my code and can't build those code to .swf file again. I wonder if the code I got from showmycode.com is correct, or is it action script? If the code I got from showmycode.com is not correct, how can I decode, edit, then encode again that "upload.swf" file?

How to save a image to HTML5 filesystem with the url of image

I am trying to use HTML5 system to store images of my website, and I find there are many example to show how to store a local image to your chrome file system but I can't find the way to get a image by web url and then store it in HTML5 file system.
This is my code, but it's wrong.
lib.ajax.get(file , function(xhr, data){
if(xhr.status == 200){
fs.root.getFile("test.jpg", {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
bb.append(data);
fileWriter.write(bb.getBlob('image/jpeg'));
callback && callback("test.jpg");
}, errorHandler);
}, errorHandler);
}
});
The problem is that browser will parse xhr response data as UTF-8,
So the point is to override MimeType:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var xhr = new XMLHttpRequest();
var photoUrl = 'http://localhost:3000/image.jpg';
xhr.open('GET', photoUrl, true);
// This stops the browser from parsing the data as UTF-8:
xhr.overrideMimeType('text/plain; charset=x-user-defined');
function stringToBinary(response) {
var byteArray = new Uint8Array(response.length);
for (var i = 0; i < response.length; i++) {
byteArray[i] = response.charCodeAt(i) & 0xff;
}
return byteArray
}
function onInitFs(fs) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
fs.root.getFile('image.jpg', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(event) {
$('body').append('<img src="' + fileEntry.toURL() + '"/>');
}
buffer = stringToBinary(xhr.response);
var blob = new Blob([ buffer ], { type: 'image/jpeg' } )
fileWriter.write(blob);
}, errorHandler );
});
}
}
xhr.send();
}
var errorHandler = function(err) {
console.log(err);
}
$(function() {
webkitStorageInfo.requestQuota(PERSISTENT, 5*1024*1024, function(grantedBytes) {
requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler)
}, errorHandler)
})
Here the function I use.
It use Blob constructor so it works on latest Chrome (thats lacks deprecated BlobBuilder) and works also on old iOS 6 that lacks 'blob' for xhr.responseType.
In comments you also see code for the deprecated BlobBuilder.
Notice: you are using XHR so CORS must be enabled!
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 2*1024*1024, onFileSystemSuccess, fail);
function onFileSystemSuccess(fileSystem) {
fs = fileSystem;
console.log('File system initialized');
saveAsset('http://www.example-site-with-cors.com/test.png');
}
function saveAsset(url, callback, failCallback) {
var filename = url.substring(url.lastIndexOf('/')+1);
// Set callback when not defined
if (!callback) {
callback = function(cached_url) {
console.log('download ok: ' + cached_url);
};
}
if (!failCallback) {
failCallback = function() {
console.log('download failed');
};
}
// Set lookupTable if not defined
if (!window.lookupTable)
window.lookupTable = {};
// BlobBuilder shim
// var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// xhr.responseType = 'blob';
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function() {
fs.root.getFile(filename, {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) {
// Save this file in the path to URL lookup table.
lookupTable[filename] = fileEntry.toURL();
callback(fileEntry.toURL());
};
writer.onerror = failCallback;
// var bb = new BlobBuilder();
var blob = new Blob([xhr.response], {type: ''});
// bb.append(xhr.response);
writer.write(blob);
// writer.write(bb.getBlob());
}, failCallback);
}, failCallback);
});
xhr.addEventListener('error', failCallback);
xhr.send();
return filename;
}
function fail(evt) {
console.log(evt.target.error.code);
}
On a modern browser supporting XMLHttpRequest Level 2 the method documented in this answer should work.
The relevant standard is explained in this blog post
The trick is to use xhr.responseType = 'blob'
var fs = .... // your fileSystem
function download(fs,url,file,win,fail) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status === 200){
fs.root.getFile(file,{create:true},function(fileEntry){
fileEntry.createWriter(function(writer){
writer.onwriteend = win;
writer.onerror = fail;
writer.write(xhr.response);
})
},fail)
} else {
fail(xhr.status);
}
}
};
xhr.send();
return xhr;
};
Based on cordova-promise-fs (disclosure: I'm the author)
I find a way to do this.
use canvans.toDataURL to transfer data format.
var img = new Image();
var cvs = document.createElement('canvas');
var ctx = cvs.getContext("2d");
img.src = file;
img.onload = function(){
cvs.width = img.width;
cvs.height = img.height;
ctx.drawImage(img, 0, 0);
var imd = cvs.toDataURL(contentType[extname]);
var ui8a = convertDataURIToBinary(imd);
var bb = new BlobBuilder();
bb.append(ui8a.buffer);
fs.root.getFile(path, {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
callback && callback("test.jpg");
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
fileWriter.write(bb.getBlob(contentType[extname]));
});
});
};
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
I get help from here jsfiddle

accessing webcam in web pages

I am developing a web application.
In my guest registration page I need to access web cam for taking images of guests.
The image which I take could be able to stored in a specified location.
Which will be the best way to perform this.
Methods using java, JSP, html, java script or any other methods are welcomed.
Answering own question, as there is a better way using HTML5 is available.
Option 1, Accessing default camera from the system
HTML
Video Tag
<br/>
<div class="camera">
<video id="video">Video stream not available.</video>
<button id="startbutton">Take photo</button>
</div>
<br/>
Canvas
<br/>
<canvas id="canvas"></canvas>
Script
var width = 320;
var height = 0;
var streaming = false;
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function (stream) {
video.srcObject = stream;
video.play();
})
.catch(function (err) {
console.log("An error occured! " + err);
});
video.addEventListener('canplay', function (ev) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
startbutton.addEventListener('click', function (ev) {
takepicture();
ev.preventDefault();
}, false);
clearphoto();
function clearphoto() {
var context = canvas.getContext('2d');
context.fillStyle = "#AAA";
context.fillRect(0, 0, canvas.width, canvas.height);
}
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var dataURL = canvas.toDataURL("image/jpeg", 0.95);
if (dataURL && dataURL != "data:,") {
var fileName = generateImageName();
uploadimage(dataURL, fileName);
} else {
alert("Image not available");
}
} else {
clearphoto();
}
}
function generateImageName() {
... generate image name logic here ...
return imageName;
}
function uploadimage(dataurl, filename) {
... upload logic here ...
}
Screen shot
Option 2, Provide a list of available cameras in the system, and let user select the camera.
HTML
<select id="videoSelect"></select>
<button id="startCameraButton">Start Camera</button>
<br/>
Video Tag
<br/>
<div class="camera">
<video id="video">Video stream not available.</video>
<button id="takePictureButton">Take photo</button>
</div>
<br/>
Canvas
<br/>
<canvas id="canvas">
</canvas>
Script
var width = 320;
var height = 0;
var streaming = false;
var localstream = null;
startCameraButton.onclick = start;
takePictureButton.onclick = takepicture;
navigator.mediaDevices.enumerateDevices()
.then(gotDevices)
.catch(function (err) {
console.log("An error occured while getting device list! " + err);
});
function gotDevices(deviceInfos) {
while (videoSelect.firstChild) {
videoSelect.removeChild(videoSelect.firstChild);
}
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
}
}
}
function start() {
stopVideo();
clearphoto();
var videoSource = videoSelect.value;
var constraints = {
audio: false,
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).then(gotDevices).catch(handleError);
}
function gotStream(stream) {
localstream = stream;
video.srcObject = stream;
video.play();
// Refresh button list in case labels have become available
return navigator.mediaDevices.enumerateDevices();
}
function handleError(error) {
console.log('navigator.getUserMedia error: ', error);
}
video.addEventListener('canplay', function (ev) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
clearphoto();
function clearphoto() {
var context = canvas.getContext('2d');
context.fillStyle = "#AAA";
context.fillRect(0, 0, canvas.width, canvas.height);
}
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var dataURL = canvas.toDataURL("image/jpeg", 0.95);
if (dataURL && dataURL != "data:,") {
var fileName = generateImageName();
fileName = fileName + ".txt"
uploadimage(dataURL, fileName);
} else {
console.log("Image not available");
}
} else {
clearphoto();
}
}
function generateImageName() {
... generate image name logic here ...
return imageName;
}
function uploadimage(dataurl, filename) {
... upload logic here ...
}
function stopVideo() {
if (localstream) {
localstream.getTracks().forEach(function (track) {
track.stop();
localstream = null;
});
}
}
Screen Shot
Option 3, let user select audio and video sources and audio output
In option 2, user can select any particular camera. On top of that if user want to select audio source and audio output source also, modify the above code with below changes.
HTML
audioInputSelect
<br/>
<select id="audioInputSelect"></select>
<br/>
audioOutputSelect
<select id="audioOutputSelect"></select>
Script
function gotDevices(deviceInfos) {
while (videoSelect.firstChild) {
videoSelect.removeChild(videoSelect.firstChild);
}
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'audioinput') {
option.text = deviceInfo.label || 'Microphone ' + (audioInputSelect.length + 1);
audioInputSelect.appendChild(option);
} else if (deviceInfo.kind === 'audiooutput') {
option.text = deviceInfo.label || 'Speaker ' + (audioOutputSelect.length + 1);
audioOutputSelect.appendChild(option);
} else if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
}
}
}
function start() {
stopVideo();
clearphoto();
var audioSource = audioInputSelect.value;
var videoSource = videoSelect.value;
var constraints = {
audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).then(gotDevices).catch(handleError);
}
jQuery Webcam Plugin does the hard work for you:
http://www.xarg.org/project/jquery-webcam-plugin/