Paste the Image from System in Html page using javascript - javascript

Hi i am creating an web chat application in that i want user can copy paste the image from desktop or can paste directly the screen shot but i am unable to achieve it.
I used following code:
$("#dummy").on("paste",function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function(event){
console.log(event.target.result)}; // data url!
reader.readAsDataURL(blob);
}
}
})
using the above code in Chrome and Firefox i am getting Clipboarddata undefined in case of image.
I tried lots of links on google but not able to reach the target.
I also tried below link from stackoverflow:
Paste an image from clipboard using JavaScript
also the below link:
http://strd6.com/2011/09/html5-javascript-pasting-image-data-in-chrome/
http://codepen.io/netsi1964/pen/IoJbg
can any one help me with complete example how to achieve It?

Demo
Works on latest chrome/firefox. Chrome implementation is simple. Firefox has restrictions that user must give command to do paste like keyboard event and editable input must be focused, so we do tricks here - on ctrl down we focusthat input field, on release unfocus.
HTML:
<canvas style="border:1px solid grey;" id="my_canvas" width="300" height="300"></canvas>
JS:
var CLIPBOARD = new CLIPBOARD_CLASS("my_canvas", true);
/**
* image pasting into canvas
*
* #param string canvas_id canvas id
* #param boolean autoresize if canvas will be resized
*/
function CLIPBOARD_CLASS(canvas_id, autoresize) {
var _self = this;
var canvas = document.getElementById(canvas_id);
var ctx = document.getElementById(canvas_id).getContext("2d");
var ctrl_pressed = false;
var reading_dom = false;
var text_top = 15;
var pasteCatcher;
var paste_mode;
//handlers
document.addEventListener('keydown', function (e) {
_self.on_keyboard_action(e);
}, false); //firefox fix
document.addEventListener('keyup', function (e) {
_self.on_keyboardup_action(e);
}, false); //firefox fix
document.addEventListener('paste', function (e) {
_self.paste_auto(e);
}, false); //official paste handler
//constructor - prepare
this.init = function () {
//if using auto
if (window.Clipboard)
return true;
pasteCatcher = document.createElement("div");
pasteCatcher.setAttribute("id", "paste_ff");
pasteCatcher.setAttribute("contenteditable", "");
pasteCatcher.style.cssText = 'opacity:0;position:fixed;top:0px;left:0px;';
pasteCatcher.style.marginLeft = "-20px";
pasteCatcher.style.width = "10px";
document.body.appendChild(pasteCatcher);
document.getElementById('paste_ff').addEventListener('DOMSubtreeModified', function () {
if (paste_mode == 'auto' || ctrl_pressed == false)
return true;
//if paste handle failed - capture pasted object manually
if (pasteCatcher.children.length == 1) {
if (pasteCatcher.firstElementChild.src != undefined) {
//image
_self.paste_createImage(pasteCatcher.firstElementChild.src);
}
}
//register cleanup after some time.
setTimeout(function () {
pasteCatcher.innerHTML = '';
}, 20);
}, false);
}();
//default paste action
this.paste_auto = function (e) {
paste_mode = '';
pasteCatcher.innerHTML = '';
var plain_text_used = false;
if (e.clipboardData) {
var items = e.clipboardData.items;
if (items) {
paste_mode = 'auto';
//access data directly
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
//image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
this.paste_createImage(source);
}
}
e.preventDefault();
}
else {
//wait for DOMSubtreeModified event
//https://bugzilla.mozilla.org/show_bug.cgi?id=891247
}
}
};
//on keyboard press -
this.on_keyboard_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey) {
if (ctrl_pressed == false)
ctrl_pressed = true;
}
//c
if (k == 86) {
if (document.activeElement != undefined && document.activeElement.type == 'text') {
//let user paste into some input
return false;
}
if (ctrl_pressed == true && !window.Clipboard)
pasteCatcher.focus();
}
};
//on kaybord release
this.on_keyboardup_action = function (event) {
k = event.keyCode;
//ctrl
if (k == 17 || event.metaKey || event.ctrlKey || event.key == 'Meta')
ctrl_pressed = false;
};
//draw image
this.paste_createImage = function (source) {
var pastedImage = new Image();
pastedImage.onload = function () {
if(autoresize == true){
//resize canvas
canvas.width = pastedImage.width;
canvas.height = pastedImage.height;
}
else{
//clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage.src = source;
};
}
Safari doesn't implement DataTransfer.items, so there's no way to
extract image data (i.e. a screenshot copied to the clipboard) in
Javascript. You can get copied files, but not data.
[From stakeoverflow post]

Chrome
Add your code to he code from codepen and give an id to the div (line 50)
Include your script as posted above with the divs id
$("#one").on("paste", function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function (event) {
console.log(event.target.result)
}; // data url!
reader.readAsDataURL(blob);
}
}
})
Make a screenshot, select the first div (that one with the id one), hit ctrl+v, the screenshot appears in the div and the imagedata is loged to console.
Firefox
Use the code I prepeared you within this fiddle
<html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
#one {
border: 1px solid black;
min-height: 100px;
min-width: 100px;
}
</style>
</head>
<body>
Copy image from clipboard in Firefox.
<br /> Select the box below and paste a image from clipboard via ctrl+v
<br /> Data printed at console
<br />
<div id="one" contenteditable="true"></div>
<script>
$(function () {
$("#one").bind("input paste", function (ev) {
window.setTimeout(function (ev) {
var input = $("#one").children()[0].src;
var s = input.split(',');
var mime = s[0];
var data = s[1];
console.log(mime);
console.log(data);
}, 300);
});
});
</script>
</body>
</html>
Chrome & Firefox combined
A combined version, using the code from #pareshm for Chrome and my code for Firefox may be found in this updated fiddle (Tested with clipboard content created via system screendump by ctrl+print and copy image part from gimp)

Related

How to validate an single/multiple image in Javascript and show error message below the input with prevent default submit?

Actually I have a form where with image input. I want to validate image for three condition like
extension should be png, jpg
size should be less than 2048kb
less than 200px x 200px is consider as dimension
I wrote an function and solve 1 and 2 issue. To solve issue 3 , I use image reader inside onload listener and when I clicked it can not prevent submit also if I remove 3, then it works fine ! Is there any solution in JS that solve above issue?
Here is a slide of my code in below.
function isImageValid(idName) {
var fileUpload = document.getElementById(idName);
var fileName = document.getElementById(idName).value;
if (typeof (fileUpload.files) != "undefined") {
for (var i=0; i<fileUpload.files.length;i++)
{
// console.log(fileUpload.files[i]);
var valid_dimension = 0;
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
var height = this.height;
var width = this.width;
if (height>200||width>200) {
valid_dimension =1;
// alert("Height and Width must not exceed 200px.");
return false;
}
// alert("Uploaded image has valid Height and Width.");
return true;
};
};
var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
var extension = fileName.split('.').pop();
if( valid_dimension ==1||size>2048||(extension!='jpg'&&extension!='JPG'&&extension!='JPEG'&&extension!='jpeg'&&extension!='png'&&extension!='PNG'))
return false;
else
return true;
}
} else {
return false;
}
}
And,
const form = document.getElementById('employee_form');
form.addEventListener('submit', (e)=>{
var is_avatar_img_valid = isImageValid('avatar');
if(is_avatar_img_valid==false){
e.preventDefault();
document.getElementById("avatar").style.borderColor = "red";
document.getElementById('avatar_validator_message').innerHTML = 'Invalid image';
}
else{
document.getElementById("avatar").style.borderColor = "black";
document.getElementById('avatar_validator_message').innerHTML = '';
}
}
The problem is reader.onload and image.onload functions are async in nature. So your form submits before these onload methods execute.
To solve this you need to follow the below steps
Prevent default in submit event handler
Pass callbacks for valid and invalid image to the isImageValid function
Manually submit the form if image is valid
Below is the code. Please mark the answer as accepted, if it helps
function isImageValid(idName, onValidCallback, onInvalidCallback) {
var fileUpload = document.getElementById(idName);
var fileName = document.getElementById(idName).value;
if (typeof (fileUpload.files) != "undefined") {
for (var i = 0; i < fileUpload.files.length; i++) {
// console.log(fileUpload.files[i]);
//--------------------
const allowedExtension = ['jpg', 'JPG', 'JPEG', 'jpeg', 'png', 'PNG'];
const maxAllowedSize = 2048;
const maxAllowedHeight = 200;
const maxAllowedWidth = 200;
const size = parseFloat(fileUpload.files[i].size / 1024).toFixed(2);
const extension = fileName.split('.').pop();
console.log({ size, extension });
//Check for valid extension and size limit
if (allowedExtension.some(ext => ext === extension) && size <= maxAllowedSize) {
//Extension and size are valid
// Now check for valid dimensions
const reader = new FileReader();
reader.readAsDataURL(fileUpload.files[i]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
//Validate the File Height and Width.
image.onload = function () {
const height = this.height;
const width = this.width;
console.log({ height, width });
if (height > maxAllowedHeight || width > maxAllowedWidth) {
// alert("Height and Width must not exceed 200px.");
//File does not meet the dimensions guidline
if (onInvalidCallback)
onInvalidCallback();
return false;
}
// alert("Uploaded image has valid Height and Width.");
//Everything is fine, form canbe submitted now
if (onValidCallback)
onValidCallback();
};
};
}
break;
}
}
else {
// There are no files selected
if (onInvalidCallback)
onInvalidCallback();
}
}
const form = document.getElementById('employee_form');
form.addEventListener('submit', (e) => {
e.preventDefault();
isImageValid('avatar', () => {
alert('going to submit');
document.getElementById("avatar").style.borderColor = "black";
document.getElementById('avatar_validator_message').innerHTML = '';
//Manually submit the form
form.submit();
},
() => {
alert('stop submit');
document.getElementById("avatar").style.borderColor = "red";
document.getElementById('avatar_validator_message').innerHTML = 'Invalid image';
}
);
return false;
});
Inside the form eventlister you need to use
e.preventDefault()
The full code looks like this
const form = document.getElementById('employee_form');
form.addEventListener('submit', (e) => {
e.preventDefault()
var is_avatar_img_valid = isImageValid('avatar');
if (is_avatar_img_valid == false) {
e.preventDefault();
document.getElementById("avatar").style.borderColor = "red";
document.getElementById('avatar_validator_message').innerHTML = 'Invalid image';
}
else {
document.getElementById("avatar").style.borderColor = "black";
document.getElementById('avatar_validator_message').innerHTML = '';
}
});

Why does this barcode detection cause Chrome or the whole Android OS to crash?

I built a barcode scanning system using Chrome's built-in BarcodeDetector. I based the work on Paul Kinlan's QR code scanner which works fine on my phone, but when I run my own code on my phone, it often causes Chrome or the whole System UI to freeze. Sometimes it gets so bad that I need to restart the phone by holding down the power button.
I have tried debugging in the Chrome developer console, but when the phone freezes, so does the developer console.
When I comment out the actual QR code detection, I can leave the page open in Chrome for 10 minutes and it just keeps running. With QR code detection running, the phone will freeze anywhere from immediately to 3 minutes later.
I put the support files (js and HTML) in a Gist - I don't think they are the issue because everything works when the barcode scanning is commented out.
My first attempt:
// Inspired by/based on on https://github.com/PaulKinlan/qrcode/blob/production/app/scripts/main.mjs
import WebCamManager from './scan/WebCamManager.js';
(function () {
'use strict';
var QRCodeCamera = function (element) {
var root = document.getElementById(element);
var cameraRoot = root.querySelector('.CameraRealtime');
var cameraManager = new WebCamManager(cameraRoot);
var cameraVideo = root.querySelector('.Camera-video');
// Offscreen canvas is supposed to help with processing speed
var cameraCanvas = new OffscreenCanvas(1,1);
var context = cameraCanvas.getContext('2d');
const detector = new BarcodeDetector({
formats: ['qr_code'],
});
cameraManager.onframeready = async function (frameData) {
cameraCanvas.width = cameraVideo.videoWidth;
cameraCanvas.height = cameraVideo.videoHeight;
context.drawImage(frameData, 0, 0, cameraVideo.videoWidth, cameraVideo.videoHeight);
if (self.onframe) {
// Comment out the line below to stop processing QR codes
await self.onframe(cameraCanvas);
}
};
var processingFrame = false;
self.onframe = async function (cameraCanvas) {
// There is a frame in the camera, what should we do with it?
if (processingFrame == false) {
processingFrame = true;
let result = await detector.detect(cameraCanvas);
processingFrame = false;
if (result === undefined || result === null || result.length === 0) {
return
};
if ('vibrate' in navigator) {
navigator.vibrate([200]);
}
cameraManager.stop();
var currentURL = new URL(window.location.href);
var newURL;
if (result[0].rawValue
&& (newURL = new URL(result[0].rawValue))
&& newURL.hostname == currentURL.hostname
&& newURL.pathname.startsWith('/pickup/qr/')
) {
window.location.href = newURL;
} else {
alert('Unsupported QR Code: ' + result[0].rawValue);
}
cameraManager.start();
}
};
};
window.addEventListener('load', function () {
var camera = new QRCodeCamera('camera');
});
})();
I also tried splitting the QR detection to a worker (worker code in Gist), but I have the same issue:
const worker = new Worker('/js/scan-worker.js');
worker.addEventListener('message', async (e) => {
if (Array.isArray(e.data)) {
var result = e.data;
if (result === undefined || result === null || result.length === 0) {
processingFrame = false;
return
};
if ('vibrate' in navigator) {
navigator.vibrate([200]);
}
var currentURL = new URL(window.location.href);
var newURL;
if (result[0].rawValue
&& (newURL = new URL(result[0].rawValue))
&& newURL.hostname == currentURL.hostname
&& newURL.pathname.startsWith('/pickup/qr/')
) {
worker.terminate();
window.location.href = newURL;
} else {
alert('Unsupported QR Code: ' + result[0].rawValue);
}
} else {
var newError = document.createElement('div');
newError.classList.add('alert', 'alert-danger');
newError.innerHTML = e.data;
errorContainer.prepend(newError);
worker.terminate();
}
processingFrame = false;
});
cameraManager.onframeready = async function (frameData) {
if (processingFrame == false) {
cameraCanvas.width = cameraVideo.videoWidth;
cameraCanvas.height = cameraVideo.videoHeight;
context.drawImage(frameData, 0, 0, cameraVideo.videoWidth, cameraVideo.videoHeight);
if (self.onframe) {
await self.onframe(cameraCanvas, context);
}
}
};
self.onframe = async function (cameraCanvas, context) {
// There is a frame in the camera, what should we do with it?
if (processingFrame == false) {
processingFrame = true;
worker.postMessage(context.getImageData(0, 0, cameraCanvas.width, cameraCanvas.height));
}
};
Not sure if this would make a difference - all the JS code is run through Laravel Mix.

Can I open the URL automaticly when I scan with WebQR

I am a programmer and I just made a simple webapp, with webview in Android studio. I have everything working except one thing. I used the WebQR set from LazarSoft. In my webapp part I have a file called webqr.js (found beneath) with the following content.
What I am trying to do is when a QR-code is scanned I want to open the result (if it is an URL) automatic in the same browser window. Now it just shows only the result.
Any help would be much appreciated.
var gCtx = null;
var gCanvas = null;
var c=0;
var stype=0;
var gUM=false;
var webkit=false;
var moz=false;
var v=null;
var imghtml='<div id="qrfile"><canvas id="out-canvas" width="320" height="240"></canvas>'+
'<div id="imghelp">drag and drop a QRCode here'+
'<br>or select a file'+
'<input type="file" onchange="handleFiles(this.files)"/>'+
'</div>'+
'</div>';
var vidhtml = '<video id="v" autoplay></video>';
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
if(files.length>0)
{
handleFiles(files);
}
else
if(dt.getData('URL'))
{
qrcode.decode(dt.getData('URL'));
}
}
function handleFiles(f)
{
var o=[];
for(var i =0;i<f.length;i++)
{
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
gCtx.clearRect(0, 0, gCanvas.width, gCanvas.height);
qrcode.decode(e.target.result);
};
})(f[i]);
reader.readAsDataURL(f[i]);
}
}
function initCanvas(w,h)
{
gCanvas = document.getElementById("qr-canvas");
gCanvas.style.width = w + "px";
gCanvas.style.height = h + "px";
gCanvas.width = w;
gCanvas.height = h;
gCtx = gCanvas.getContext("2d");
gCtx.clearRect(0, 0, w, h);
}
function captureToCanvas() {
if(stype!=1)
return;
if(gUM)
{
try{
gCtx.drawImage(v,0,0);
try{
qrcode.decode();
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
}
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function read(a)
{
var html="<br>";
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
html+="<a target='_blank' href='"+a+"'>"+a+"</a><br>";
html+="<b>"+htmlEntities(a)+"</b><br><br>";
document.getElementById("result").innerHTML=html;
}
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
function success(stream) {
if(webkit)
v.src = window.webkitURL.createObjectURL(stream);
else
if(moz)
{
v.mozSrcObject = stream;
v.play();
}
else
v.src = stream;
gUM=true;
setTimeout(captureToCanvas, 500);
}
function error(error) {
gUM=false;
return;
}
function load()
{
if(isCanvasSupported() && window.File && window.FileReader)
{
initCanvas(800, 600);
qrcode.callback = read;
document.getElementById("mainbody").style.display="inline";
setwebcam();
}
else
{
document.getElementById("mainbody").style.display="inline";
document.getElementById("mainbody").innerHTML='<p id="mp1">QR code scanner for HTML5 capable browsers</p><br>'+
'<br><p id="mp2">sorry your browser is not supported</p><br><br>'+
'<p id="mp1">try <img src="firefox.png"/> or <img src="chrome_logo.gif"/> or <img src="Opera-logo.png"/></p>';
}
}
function setwebcam()
{
document.getElementById("result").innerHTML="- scanning -";
if(stype==1)
{
setTimeout(captureToCanvas, 500);
return;
}
var n=navigator;
document.getElementById("outdiv").innerHTML = vidhtml;
v=document.getElementById("v");
if(n.getUserMedia)
n.getUserMedia({video: true, audio: false}, success, error);
else
if(n.webkitGetUserMedia)
{
webkit=true;
n.webkitGetUserMedia({video:true, audio: false}, success, error);
}
else
if(n.mozGetUserMedia)
{
moz=true;
n.mozGetUserMedia({video: true, audio: false}, success, error);
}
//document.getElementById("qrimg").src="qrimg2.png";
//document.getElementById("webcamimg").src="webcam.png";
document.getElementById("qrimg").style.opacity=0.2;
document.getElementById("webcamimg").style.opacity=1.0;
stype=1;
setTimeout(captureToCanvas, 500);
}
function setimg()
{
document.getElementById("result").innerHTML="";
if(stype==2)
return;
document.getElementById("outdiv").innerHTML = imghtml;
//document.getElementById("qrimg").src="qrimg.png";
//document.getElementById("webcamimg").src="webcam2.png";
document.getElementById("qrimg").style.opacity=1.0;
document.getElementById("webcamimg").style.opacity=0.2;
var qrfile = document.getElementById("qrfile");
qrfile.addEventListener("dragenter", dragenter, false);
qrfile.addEventListener("dragover", dragover, false);
qrfile.addEventListener("drop", drop, false);
stype=2;
}
Welcome to JavaScript, may you long prosper with its many uses!
As you are new to JavaScript, you may not know its Browser API, but fear not!
What you are looking for is window.open
Its syntax is simple:
window.open("http://example.com")
So, when you get the url from you qr decoder, all you have to do is window.open the URL, and viola, the window will appear in a new tab!
Now if you want to open in the same browser window, then you want to use
window.location.replace("http://example.com")
This will redirect the same tab, instead of a new one!
To implement this in your program, take a look at this read function:
function read(a) {
// If it's a URL, open in here
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
window.location.replace(a)
}
Hope I could help!

Android Web Console: UncaughtReferenceError: Worker is not defined

I'm pretty new about javascript. after a long search I couldn't find why but looks like popular browsers does somework about this definition new Worker("BarcodeWorker.js") as their base js support but Android WebView. Orginal code is from Eddie Larsson barcode reader on github. Thanks.
<!DOCTYPE html>
<meta charset=utf-8>
<html lang="en">
<head>
<title>BarcodeReader</title>
</head>
<body>
<div id="container">
<img width="640" height="480" src="about:blank" alt="" id="picture">
<input id="Take-Picture" type="file" accept="image/*;capture=camera" />
<p id="textbit"></p>
</div>
<script type="text/javascript">
var takePicture = document.querySelector("#Take-Picture"),
showPicture = document.querySelector("#picture");
Result = document.querySelector("#textbit");
Canvas = document.createElement("canvas");
Canvas.width=640;
Canvas.height=480;
var resultArray = [];
ctx = Canvas.getContext("2d");
var workerCount = 0;
function receiveMessage(e) {
if(e.data.success === "log") {
console.log(e.data.result);
return;
}
workerCount--;
if(e.data.success){
var tempArray = e.data.result;
for(var i = 0; i < tempArray.length; i++) {
if(resultArray.indexOf(tempArray[i]) == -1) {
resultArray.push(tempArray[i]);
}
}
Result.innerHTML=resultArray.join("<br />");
}else{
if(resultArray.length === 0 && workerCount === 0) {
Result.innerHTML="Decoding failed.";
}
}
}
//Where the issue starts
var script='';
var DecodeWorker = new Worker("DecoderWorker.js");
var RightWorker = new Worker("DecoderWorker.js");
var LeftWorker = new Worker("DecoderWorker.js");
var FlipWorker = new Worker("DecoderWorker.js");
DecodeWorker.onmessage = receiveMessage;
RightWorker.onmessage = receiveMessage;
LeftWorker.onmessage = receiveMessage;
FlipWorker.onmessage = receiveMessage;
if(takePicture && showPicture) {
takePicture.onchange = function (event) {
var files = event.target.files
if (files && files.length > 0) {
file = files[0];
try {
var URL = window.URL || window.webkitURL;
var imgURL = URL.createObjectURL(file);
showPicture.src = imgURL;
URL.revokeObjectURL(imgURL);
DecodeBar()
}
catch (e) {
try {
var fileReader = new FileReader();
fileReader.onload = function (event) {
showPicture.src = event.target.result;
};
fileReader.readAsDataURL(file);
DecodeBar()
}
catch (e) {
Result.innerHTML = "Neither createObjectURL or FileReader are supported";
}
}
}
};
}
function DecodeBar(){
showPicture.onload = function(){
ctx.drawImage(showPicture,0,0,Canvas.width,Canvas.height);
resultArray = [];
workerCount = 4;
Result.innerHTML="";
DecodeWorker.postMessage({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "normal"});
RightWorker.postMessage({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "right"});
LeftWorker.postMessage({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "left"});
FlipWorker.postMessage({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "flip"});
}
}
</script>
</body>
</html>
It looks like Web Workers aren't available to you, (and aren't available in current versions of Opera Mini and the Android browser [but are in mobile Chrome!]). They're a way to put some resource-intensive tasks in another thread, so your main thread doesn't get held up (useful to prevent the app/page appearing to freeze for a moment).
Luckily, they shouldn't be necessary for your code to work. You'll need to move the javascript from "DecoderWorker.js" into the scope of your page, and rework/remove the message and onmessage events, instead calling the function(s) copied from the worker directly.
UPDATE: Here's a working fiddle to get you started. I just replaced e.data with options and changed the message events to functions:
/* From reader.html */
function receiveMessage(options) {
if(options.success === "log") {
console.log(options.result);
return;
}
workerCount--;
if(options.success){
var tempArray = options.result;
for(var i = 0; i < tempArray.length; i++) {
if(resultArray.indexOf(tempArray[i]) == -1) {
resultArray.push(tempArray[i]);
}
}
Result.innerHTML=resultArray.join("<br />");
}else{
if(resultArray.length === 0 && workerCount === 0) {
Result.innerHTML="Decoding failed.";
}
}
}
function DecodeBar(){
showPicture.onload = function(){
ctx.drawImage(showPicture,0,0,Canvas.width,Canvas.height);
resultArray = [];
workerCount = 4;
Result.innerHTML="";
ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "normal"}, receiveMessage);
ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "right"}, receiveMessage);
ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "left"}, receiveMessage);
ReadBarcode({pixels: ctx.getImageData(0,0,Canvas.width,Canvas.height).data, cmd: "flip"}, receiveMessage);
}
}
/* From the last onmessage handler in DecoderWorker.js */
function ReadBarcode(options, callback) {
Image = {
data: new Uint8ClampedArray(options.pixels),
width: 640,
height: 480
}
var availableFormats = ["Code128","Code93","Code39","EAN-13"];
FormatPriority = [];
var skipList = [];
if(typeof options.priority != 'undefined') {
FormatPriority = options.priority;
}
for(var i = 0; i < availableFormats.length; i++) {
if(FormatPriority.indexOf(availableFormats[i]) == -1) {
FormatPriority.push(availableFormats[i]);
}
}
if(typeof options.skip != 'undefined') {
skipList = options.skip;
}
for(var i = 0; i < skipList.length; i++) {
if(FormatPriority.indexOf(skipList[i]) != -1) {
FormatPriority.splice(FormatPriority.indexOf(skipList[i]),1);
}
}
CreateTable();
switch(options.cmd) {
case "flip":
flipTable();
break;
case "right":
rotateTableRight();
break;
case "left":
rotateTableLeft();
break;
case "normal":
break;
}
var FinalResult = Main();
if(FinalResult.length > 0) {
callback({result: FinalResult, success: true});
} else {
callback({result: FinalResult, success: false});
}
}

HTML5 read video metadata of mp4

Using HTML5 I am trying to get the attribute (ie rotation), located in the header of a mp4 (I play it using a video tag), to do this I am trying to get the bytes that make up the header, and knowing the structure, find this atom.
Does anyone know how to do this in javascript?
You can use mediainfo.js,
It's a porting of mediainfo (cpp) in javascript compiled with emsciptem.
Here is a working example: https://mediainfo.js.org/
You will need to include the js/mediainfo.js file and put mediainfo.js.mem file in the same folder.
You need to check the sources on this file to see how it works:
https://mediainfo.js.org/js/mediainfopage.js
[...]
function parseFile(file) {
if (processing) {
return;
}
processing = true;
[...]
var fileSize = file.size, offset = 0, state = 0, seekTo = -1, seek = null;
mi.open_buffer_init(fileSize, offset);
var processChunk = function(e) {
var l;
if (e.target.error === null) {
var chunk = new Uint8Array(e.target.result);
l = chunk.length;
state = mi.open_buffer_continue(chunk, l);
var seekTo = -1;
var seekToLow = mi.open_buffer_continue_goto_get_lower();
var seekToHigh = mi.open_buffer_continue_goto_get_upper();
if (seekToLow == -1 && seekToHigh == -1) {
seekTo = -1;
} else if (seekToLow < 0) {
seekTo = seekToLow + 4294967296 + (seekToHigh * 4294967296);
} else {
seekTo = seekToLow + (seekToHigh * 4294967296);
}
if(seekTo === -1){
offset += l;
}else{
offset = seekTo;
mi.open_buffer_init(fileSize, seekTo);
}
chunk = null;
} else {
var msg = 'An error happened reading your file!';
console.err(msg, e.target.error);
processingDone();
alert(msg);
return;
}
// bit 4 set means finalized
if (state&0x08) {
var result = mi.inform();
mi.close();
addResult(file.name, result);
processingDone();
return;
}
seek(l);
};
function processingDone() {
processing = false;
$status.hide();
$cancel.hide();
$dropcontrols.fadeIn();
$fileinput.val('');
}
seek = function(length) {
if (processing) {
var r = new FileReader();
var blob = file.slice(offset, length + offset);
r.onload = processChunk;
r.readAsArrayBuffer(blob);
}
else {
mi.close();
processingDone();
}
};
// start
seek(CHUNK_SIZE);
}
[...]
// init mediainfo
miLib = MediaInfo(function() {
console.debug('MediaInfo ready');
$loader.fadeOut(function() {
$dropcontrols.fadeIn();
window['miLib'] = miLib; // debug
mi = new miLib.MediaInfo();
$fileinput.on('change', function(e) {
var el = $fileinput.get(0);
if (el.files.length > 0) {
parseFile(el.files[0]);
}
});
});
Here is the Github address with the sources of the project: https://github.com/buzz/mediainfo.js
I do not think you can extract such detailed metadata from a video, using HTML5 and its video-tag. The only things you can extract (video length, video tracks, etc.) are listed here:
http://www.w3schools.com/tags/ref_av_dom.asp
Of course, there might be special additional methods available in some browsers, but there is no "general" approach - you would need more than the existing methods of HTML5.

Categories

Resources