利用jquery webcam 拍照.webcam拍照只能拍320*240的照片吗

Engineer, Systems Architect and DBAThe 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!OverviewThis 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 examplejQuery | Available CamerasIf you activate the filter with the button on the right side of the picture, methods of my already published
will be used to distort the colors of the Canvas.General information about the interfaceThe 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 ParameterwidthThe width of the flash movie.heightThe 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.modeThe 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.swffilePoints 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 ). Thereby, the file is only one third as large as the original.onTick, onSave, onCaptureThese callbacks are described in detail below, since they change with each mode.onLoadThe 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()debugThe 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 InterfaceThe 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!&);
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(&;&);
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp && 16) & 0
img.data[pos + 1] = (tmp && 8) & 0
img.data[pos + 2] = tmp & 0
img.data[pos + 3] = 0
if (pos &= 4 * 320 * 240) {
ctx.putImageData(img, 0, 0);
}Save InterfaceFrom 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 FlashThe 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(";");
for(var i = 0; i & 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp && 16) & 0
img.data[pos + 1] = (tmp && 8) & 0
img.data[pos + 2] = tmp & 0
img.data[pos + 3] = 0
if (pos &= 4 * 320 * 240) {
ctx.putImageData(img, 0, 0);
$.post("/upload.php", {type: "data", image: canvas.toDataURL("image/png")});
saveCB = function(data) {
image.push(data);
pos+= 4 * 320;
if (pos &= 4 * 320 * 240) {
$.post("/upload.php", {type: "pixel", image: image.join('|')});
$("#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);
// input is in format: data:image/base64,...
$im = imagecreatefrompng($_POST['image']);
// do something with $im
?&Stream interfaceThe 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 binaryIf 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
makeHint about empty screens after recompilationThere is a bug in the current version of swfmill. Please try to downgrade swfmill to 2.0.12, which fixes the issue!You should Follow me!Related readMy Rating: ★★★★☆& 2008 & 2018 Robert Eisele All rights reserved.JQuery WebCam 网页拍照配置 保存服务端,有需要的朋友可以参考下。网页头部引入
&script src=&jquery.min.js& type=&text/javascript&&&/script&
&script src=&jquery.webcam.min.js& type=&text/javascript&&&/script&
初始化摄像头
var pos = 0, ctx = null, saveCB, image = [];
var pos = 0;
var w = 320;
var h = 240;
$(function () {
var canvas = document.createElement(&canvas&);
canvas.setAttribute(&#39;width&#39;, 320);
canvas.setAttribute(&#39;height&#39;, 240);
if (canvas.toDataURL) {
ctx = canvas.getContext(&2d&);
image = ctx.getImageData(0, 0, 320, 240);
saveCB = function (data) {
var col = data.split(&;&);
for (var i = 0; i & 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp && 16) & 0
img.data[pos + 1] = (tmp && 8) & 0
img.data[pos + 2] = tmp & 0
img.data[pos + 3] = 0
if (pos &= 4 * 320 * 240) {
ctx.putImageData(img, 0, 0);
$.post(&UploadImage.ashx&, { type: &data&, image: canvas.toDataURL(&image/png&) }, function (msg) {
var msgjson = JSON.parse(msg);
flashcam(msgjson.code, msgjson.picUrl);
saveCB = function (data) {
image.push(data);
pos += 4 * 320;
if (pos &= 4 * 320 * 240) {
$.post(&UploadImage.ashx&, { type: &pixel&, image: image.join(&#39;|&#39;) }, function (msg) {
var msgjson = JSON.parse(msg);
flashcam(msgjson.code, msgjson.picUrl);
&span style=&white-space:pre&& &/span&
//延时加载flash
&#160; &#160; &#160; &#160; &#160; &#160; setTimeout(callFlash, 500);
function callFlash() {
$(&#Camera&).webcam({
width: 320,
height: 240,
mode: &callback&,
swffile: &jscam.swf?& + Math.random(),
onTick: function () { },
onSave: saveCB,
onCapture: function () {
webcam.save();
debug: function () { },
onLoad: function () { }
调用webcam.capture();进行拍照&div id=&Camera&&&/div&&div id=&avatar_priview& style=&width: 320px&&&/div&&input type=&button& onclick=& webcam.capture();& value=&拍照&/&
服务器端解析
/// &summary&
/// UploadImage 的摘要说明
/// &/summary&
public class UploadImage : IHttpHandler
#region 静态字段
static JavaScriptSerializer jss = new JavaScriptSerializer();
UpFileResponseModel fail1 = new UpFileResponseModel() { code = -1, msg = &&, picUrl = && };
UpFileResponseModel fail2 = new UpFileResponseModel() { code = -2, msg = &&, picUrl = && };
#endregion
public void ProcessRequest(HttpContext context)
context.Response.ContentType = &text/html&;
var imageStr = context.Request[&image&].Replace(&data:image/base64,&, &&).Trim();
string fileName = DateTime.Now.Ticks.ToString();
var path = &~/upload/& + fileN//上传至upload文件夹
Base64StringToImage(path, imageStr);
UpFileResponseModel model = new UpFileResponseModel() { code = 1, msg = &\uf&, picUrl = &/upload/& + fileName + &.jpg& };
context.Response.Write( jss.Serialize(model));
public bool IsReusable
private byte[] String_To_Bytes2(string strInput)
int numBytes = (strInput.Length) / 2;
byte[] bytes = new byte[numBytes];
for (int x = 0; x & numB ++x)
bytes[x] = Convert.ToByte(strInput.Substring(x * 2, 2), 16);
/// &summary&
/// base64编码的文本 转为
/// &/summary&
/// &param name=&txtFilePath&&文件相对路径&/param&
/// &param name=&str&&图片字符串&/param&
private void Base64StringToImage(string txtFilePath, string str)
String inputStr =
byte[] arr = Convert.FromBase64String(inputStr);
MemoryStream ms = new MemoryStream(arr);
Bitmap bmp = new Bitmap(ms);
bmp.Save(System.Web.HttpContext.Current.Server.MapPath(txtFilePath) + &.jpg&, System.Drawing.Imaging.ImageFormat.Jpeg);
//bmp.Save(txtFileName + &.bmp&, ImageFormat.Bmp);
//bmp.Save(txtFileName + &.gif&, ImageFormat.Gif);
//bmp.Save(txtFileName + &.png&, ImageFormat.Png);
ms.Close();
//imgPhoto.ImageUrl = txtFilePath + &.jpg&;
//MessageBox.Show(&转换成功!&);
catch (Exception ex)
}&pre name=&code& class=&csharp&&//上传图片返回模型&span style=&font-family: Arial, Helvetica, sans-&&public class UpFileResponseModel&/span&{
public int code { }
public string msg { }
public string picUrl { }&&&&&&&&&&&&
31915人浏览
185901人浏览
81047人浏览
99115人浏览
38189人浏览
12883人浏览
&&&&&&&&&&&&
1451张照片
Kid A的日记
黑暗观察就是以黑暗为观察对像的活动,而黑暗观察家就是观察黑暗的人,其中的佼佼...
&&&&&&&&&&&&
&&&&&&&&&&&&
&&&&&&&&&&&&
&&&&&&&&&&&&
15447 个成员
44857 个成员
22477 个成员
24729 个成员
10602 个成员
111886 个成员
93348 个成员
92642 个成员
35199 个成员
3801 个成员
15598 个成员
&&&&&&&&&&&&
〔日〕向田邦子...
〔美〕A.J....
〔日〕是枝裕和...
〔瑞典〕弗雷德...
原创数字作品
&&&&&&&&&&&&
流派: 摇滚 Rock
21878人关注
流派: 电子 Electronica
24405人关注
流派: 世界音乐 World
1584人关注
流派: 民谣 Folk
8262人关注
流派: 原声 Soundtrack
豆瓣新碟榜
&&&&&&&&&&&&
&&&&&&&&&&&&
久石让-宫崎骏
我开车时听什么
夜里什么都没有
三十种乐器
&&&&&&&&&&&&
&&&&&&&&&&&&
无锡 · 本周热门活动
&&&&&&&&&&&&
无锡市人民大会堂 无锡市南...
无锡新文化宫 无锡新文化宫
无锡大剧院-歌剧厅 江苏省...
无锡大剧院-歌剧厅 江苏省...
douban.com, all rights reserved 北京豆网科技有限公司
京ICP备号 网络视听许可证号
京网文[8号
&&新出网证(京)字129号
违法和不良信息举报电话:&
电话:12377问说网手机版
躺着 站着 跪着轻松访问
问说网 / 蜀ICP备号
感谢您对问说网的支持,提出您在使用过程中遇到的问题或宝贵建议,您的反馈对我们产品的完善有很大帮助。
您的反馈我们已收到!
感谢您提供的宝贵意见,我们会在1-2个工作日,通过您留下的联系方式将处理结果反馈给您!博主最新文章
博主热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)

我要回帖

更多关于 jquery webcam 拍照 的文章

 

随机推荐