jQuery webcam plugin

The jQuery webcam plugin is a transparent layer to communicate with a camera directly in JavaScript.

As there is native support for webcams in modern browsers, it would be great if you could add this feature to the project and use the flash-version as a fallback for older ones. I don't have time for this project at the moment, so a pull request would be great!

Overview

This plugin provides three different modes to access a webcam through a small API directly with JavaScript - or more precisely jQuery. Thus, it is possible to bring the image on a Canvas (callback mode), to store the image on the server (save mode) and to stream the live image of the Flash element on a Canvas (stream mode). If you just want to download the plugin, click here:

jQuery webcam example

jQuery

Take a picture after 3 seconds | Take a picture instantly

Available Cameras

  • HP Webcam [2 MP Fixed]: HP Webc (V4L2)

If you activate the filter with the button on the right side of the picture, methods of my already published jQuery plugin xcolor will be used to distort the colors of the Canvas.

General information about the interface

The following snippet describes the interface of the webcam API:

$("#camera").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "/download/jscam_canvas_only.swf",
onTick: function() {},
onSave: function() {},
onCapture: function() {},
debug: function() {},
onLoad: function() {}
});

Config Parameter

width
The width of the flash movie.

height
The
height of the flash movie. Both parameters have to be changed in the
Flash file as well. Follow the instructions below to recompile the swf
after the size change.

mode
The storage mode can be one of the following: callback, save, stream. Details about the usage of each parameter can be found under the according heading below.

swffile
Points
to the swf file of the Flash movie, which provides the webcam API.
There are two swf files provided via the download archive: jscam.swf, which provides the full API and jscam_canvas_only.swf which have no embedded JPEG library (I embedded an adjusted JPGEncoder of the AS 3 corelib). Thereby, the file is only one third as large as the original.

onTick, onSave, onCapture
These callbacks are described in detail below, since they change with each mode.

onLoad
The onLoad
callback is called as soon as the registration of the interface is
done. In the example above, I use the callback to get a list of all
cameras available:

onLoad: function() {

    var cams = webcam.getCameraList();
for(var i in cams) {
jQuery("#cams").append("<li>" + cams[i] + "</li>");
}
}

Once the onLoad callback is called, a global object window.webcam is available, which provides the following methods:

  • capture([delay])
    Captures an image internally.
  • save([file])
    Saves the captured image accordingly to the storage mode.
  • getCameraList()
    Get's an array of available cameras. If no camera is installed, an error is thrown and an empty array is returned.
  • setCamera([index])
    Switches to a different camera. The parameter is the index of the element in the resulting array of getCameraList()

debug
The debug
callback is called whenever there is a note or an error you should be
notified. In the example above, I just replace the html content of the
output container:

debug: function (type, string) {
$("#status").html(type + ": " + string);
}

Callback Interface

The callback mode is used to get the raw data via a callback method to write it on a canvas element for example. The example above uses the callback mode.

As for the processing, one can imagine how it works as follows: Once the user has completely loaded the entire page and has accepted the security setting of Flash, she should be able to see herself. Then, the user triggers the method window.capture(). This may optionally receive a parameter that specifies the time to wait until the image is shot. To view the passage of time, the method onTick() is called after every second. The received parameter of this method is the amount of seconds remaining. In the example above, I simply change the status message like this:

onTick: function(remain) {

    if (0 == remain) {
jQuery("#status").text("Cheese!");
} else {
jQuery("#status").text(remain + " seconds remaining...");
}
}

Is copying finished, the onCapture callback is called, which in the example of above immediately calls the method webcam.save() to ultimately write the image to the canvas. The sample code also contains a small gimmick to simulate a flash using a lightbox and jQuery's fadeOut() fx method.

onCapture: function () {

	jQuery("#flash").css("display", "block");
jQuery("#flash").fadeOut("fast", function () {
jQuery("#flash").css("opacity", 1);
}); webcam.save();
}

In callback mode, for every line the callback onSave() is invoked, which gets an integer CSV of color values (separator is the semicolon). To write the data on the canvas, I use the following method in the example above:

onSave: function(data) {

    var col = data.split(";");
var img = image; for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
} if (pos >= 4 * 320 * 240) {
ctx.putImageData(img, 0, 0);
pos = 0;
}
}

Save Interface

From the view of processing, the save mode is almost identical to the callback mode. The only difference is that the webcam.save() method get's the file name passed as parameter. Then the shot photo is sent via HTTP_RAW_POST_DATA to the server and can be read for example with the following snippet to store or further process it in any way (Warning, input validation is not considered here!).

webcam.save('/upload.php');

And on the server side, you get the image like this:

<?php

$str = file_get_contents("php://input");
file_put_contents("/tmp/upload.jpg", pack("H*", $str)); ?>

Alternative method to the upload via Flash

The Flash method has several problems. The implementation can lock the entire Flash movie and in the worst case the whole browser until the picture was uploaded sucessfully. A better approach is Ajax to upload the image asynchronously. Take a look at this example. It uploads a simple picture CSV if canvas elements are not implemented in the browser and sends a data url formatted string otherwise:

$(function() {

	var pos = 0, ctx = null, saveCB, image = [];

	var canvas = document.createElement("canvas");
canvas.setAttribute('width', 320);
canvas.setAttribute('height', 240); if (canvas.toDataURL) { ctx = canvas.getContext("2d"); image = ctx.getImageData(0, 0, 320, 240); saveCB = function(data) { var col = data.split(";");
var img = image; for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
} if (pos >= 4 * 320 * 240) {
ctx.putImageData(img, 0, 0);
$.post("/upload.php", {type: "data", image: canvas.toDataURL("image/png")});
pos = 0;
}
}; } else { saveCB = function(data) {
image.push(data); pos+= 4 * 320; if (pos >= 4 * 320 * 240) {
$.post("/upload.php", {type: "pixel", image: image.join('|')});
pos = 0;
}
};
} $("#webcam").webcam({ width: 320,
height: 240,
mode: "callback",
swffile: "/download/jscam_canvas_only.swf", onSave: saveCB, onCapture: function () {
webcam.save();
}, debug: function (type, string) {
console.log(type + ": " + string);
}
}); });

The server could then do something like this:

<?php

if ($_POST['type'] == "pixel") {
// input is in format 1,2,3...|1,2,3...|...
$im = imagecreatetruecolor(320, 240); foreach (explode("|", $_POST['image']) as $y => $csv) {
foreach (explode(";", $csv) as $x => $color) {
imagesetpixel($im, $x, $y, $color);
}
}
} else {
// input is in format: data:image/png;base64,...
$im = imagecreatefrompng($_POST['image']);
} // do something with $im ?>

Stream interface

The stream mode is also quite the same procedure as the callback mode, with the difference that the onSave callback is called non-stop. The streaming starts with the method webcam.capture(). The webcam.save() method has no further effect.

Recompile the Flash binary

If you've made changes to the code or did just adjust the size of the video in the XML specification file, you can easily recompile the swf file from Linux console with the provided Makefile. You are required to install the two open source projects swfmill and mtasc that can be easily installed using apt-get under Debian/Ubuntu:

apt-get install swfmill mtasc
vim src/jscam.xml
make

Hint about empty screens after recompilation

There is a bug in the current version of swfmill. Please try to downgrade swfmill to 2.0.12, which fixes the issue!

jQuery webcam plugin的更多相关文章

  1. jQuery Webcam Plugin jscam.swf文件反编译工具使用说明

    jQuery webcam plugin是一个在ie,firefox,chrome下都可以用的摄像头摄像及拍照用的插件. (http://www.xarg.org/project/jquery-web ...

  2. 30个非常流行的提示信息插件(jQuery Tooltip Plugin)

    在网站的设计中,提示信息是非常细微的功能,但是起着非常重要的作用.如果你的网站中提示信息做的比较好,会给浏览者留下非常深刻的印象,同时也会起到非常好的网站宣传效果,下面介绍了30个比较流行提示信息插件 ...

  3. JQuery多媒体插件jQuery Media Plugin使用详解

    malsup jquery media plugin 该插件可以播放多种类型的多媒体文件包括:Flash, Quicktime, Windows Media Player, Real Player, ...

  4. jQuery DataTables Plugin Meets C#

    Over the weekend, I was doing some work on the internal CMS we use over at eagleenvision.net and I w ...

  5. jQuery Validation Plugin学习

    http://blog.csdn.net/violet_day/article/details/14109261 jQuery Validation Plugin Demo 一.默认校验规则 (1)r ...

  6. (转)jQuery Validation Plugin客户端表单证验插件

    jQuery Validation Plugin客户端表单验证插件 官方文档:http://jqueryvalidation.org/documentation/ 官方demo:http://jque ...

  7. 表单验证的validate.js插件---jQuery Validation Plugin

    早上在公交车上看了一个关于慕课网的教程<表单验证的validate.js插件---jQuery Validation Plugin>,正好可以用到自己近期开发简易微博的注册页面和登录页面, ...

  8. jQuery validator plugin 之 custom methods 案例1:multi email

    1.add method jQuery.validator.addMethod( "multiemail", function (value, element) { var ema ...

  9. Using The jQuery Migrate Plugin

    jQuery( html [, ownerDocument ] )Returns: jQuery Description: Creates DOM elements on the fly from t ...

随机推荐

  1. Linux 操作系统下的环境变量设置

    Linux下的环境变量设置 by:授客 QQ:1033553122 1.  问题描述 linux输入命令时经常会出现提示:xxx:Command not found 2.  原因分析 Command ...

  2. 聊聊HTTP gzip压缩与常见的Android网络框架

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/5835990.html 进入主题之前,我们先来看一下客户端与服 ...

  3. TensorFlow实现梯度下降

    # -*- coding: utf-8 -*- """ Created on Mon Oct 15 17:38:39 2018 @author: zhen "& ...

  4. C语言程序试题

    一个无向连通图G点上的哈密尔顿(Hamiltion)回路是指从图G上的某个顶点出发,经过图上所有其他顶点一次且仅一次,最后回到该顶点的路劲.一种求解无向图上哈密尔顿回路算法的基础实现如下: 假设图G存 ...

  5. Linksys EA6500刷ddwrt成功记

    网上刷Linksys EA6500的资料不多,然后又绕了好多个弯子,自己记录备忘. 首先EA6500有两个版本v1和v2,对应的固件不同. 区分方法: 1.v1的背后是两个颜色一样的usb2.0 2. ...

  6. Kubernetes的搭建与配置(一):集群环境搭建

    1.环境介绍及准备: 1.1 物理机操作系统 物理机操作系统采用Centos7.3 64位,细节如下. [root@localhost ~]# uname -a Linux localhost.loc ...

  7. 【PAT】B1078 字符串压缩与解压(20 分)

    主函数接收下第一个字符,接着一个分支就转到两个函数中的一个 1.压缩简单,只要与下一个一样就只计数,如果不同了就直接输出 2.至于解压不知道数字是几位数,所以我直接用了sscanf,然后判断是几位数字 ...

  8. Linux 小知识翻译 - 「命令行的提示符」

    这次,聊聊关于「命令行提示符」的相关内容. bash之类的Shell程序是操作Linux所不可缺少的东西.其中bash的提示符也有承担了很重要的作用. 「命令行提示符」的英文是「command pro ...

  9. 在excel中将缺失数据全部用0补齐

    先ctrl+H ,出现如下对话框 点击“定位”,选择“空值” 在表格中空的位置上编辑栏输入0,CTRL+ENTER,即可将缺失数据全部用0补齐.

  10. 计算机基础-CPU

    CPU(Central Processing Unit中央处理器)由运算器和控制器组成--微机性能的集成度最高的核心部件 1.金属触点 2.附带散热器 风冷式 热管散热式 水冷式等 扣具结构要和CPU ...