Calling camera with jQuery webcam plugin

Time:2020-12-28

Welcome to personal website

brief introduction

The original project encountered a call to the camera function, PHP white encountered this situation immediately to the Internet search, the final use
https://www.helloweba.com/vie…, too bad, the author did not say how to use, if you use the framework development is very troublesome

Today, I found a more flexible plug-in jQuery webcam plugin againhttp://www.xarg.org/project/j…【demo】

usage method

Some references:http://www.cnblogs.com/loyung…

  • Width: 320, height: 240, / / considering the display effect, 320 * 240 is the standard display mode and cannot be changed (plug-in is hard). If you want to change the size, you can change it jscam.swf source file
  • The mode: / / – storage mode can be called back | save | stream in the following three ways
  • Swffile: / /: you can select jscam after decompression_ canvas_ only.swf or jscam.swf ,jscam_ canvas_ Only speeds up the efficiency of each device call because it has only jscam.swf 1 / 3 of the total
  • Ontick: function (remain) {} / / trigger regularly and take photos regularly
  • Onsave: / / key place, set the background of submitting data processing to set the image parameters
  • Oncapture: / / click to take a picture and save
  • Onload: / / plug-in loading event. Usually, the device list is listed here
jQuery("#webcam").webcam({

    width: 320,
    height: 240,
    mode: "callback",
    swffile: "/jscam_canvas_only.swf", // canvas only doesn't implement a jpeg encoder, so the file is much smaller

    onTick: function(remain) {

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

    onSave: function(data) {

        var col = data.split(";");
    // Work with the picture. Picture-data is encoded as an array of arrays... Not really nice, though =/
    },

    onCapture: function () {
        webcam.save();

       // Show a flash for example
    },

    debug: function (type, string) {
        // Write debug information to console.log() or a div, ...
    },

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

The JS code above defines another < div id = “webcam” > < / div > to open the camera, but there are still some modifications to interact with PHP

Full demo

The comments in the following code are for personal understanding only, not for the original author’s reference only

html+js

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery-webcam-master</title>
    <link href="cs.css" rel="stylesheet" type="text/css">
    <script></script>
    <script></script>
    <script type="text/javascript">
        $(function() {

            var pos = 0, ctx = null, saveCB, image = [];
//Create a canvas to specify the width and height
            var canvas = document.createElement("canvas");
            canvas.setAttribute('width', 320);
            canvas.setAttribute('height', 240);
//If the canvas is created successfully
            if (canvas.toDataURL) {
//Set the canvas to 2D and support 3D in the future
                ctx = canvas.getContext("2d");
//Screenshot 320 * 240, that is, the entire canvas as a valid area (cutx?)
                image = ctx.getImageData(0, 0, 320, 240);

                saveCB = function(data) {
//Cutting data into arrays
                    var col = data.split(";");
                    var img = image;
//Draw an image (I don't quite understand the algorithm here)
//The parameter data is only the data of each line. For example, for a 320 * 240 photo, a complete photo needs 240 data, and each data has 320 RGB
                    for(var i = 0; i < 320; i++) {
                        //Convert to decimal
                        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;
                    }
//Send it to PHP when drawing a 320 * 240 pixel image
                    if (pos >= 4 * 320 * 240) {
//Put the image on the canvas and output it in PNG format
                        ctx.putImageData(img, 0, 0);
                        $.post("upload.php", {type: "data", image: canvas.toDataURL("image/png")});
                        pos = 0;
                    }
                };

            } else {
                saveCB = function(data) {
//Put the data into image bit by bit
                    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: "jscam_canvas_only.swf",

                onSave: saveCB,

                onCapture: function () {
                    webcam.save();
                },

                debug: function (type, string) {
                    console.log(type + ": " + string);
                }
            });
//            /**
//* get the content of canvas getimagedata
//* put content back on canvas putimagedata
//* get every pixel of imgdata ImgData.data
//* getimagedata (abscissa of starting point, ordinate of starting point, acquired width, acquired height)
//* putimagedata (abscissa of drawing point, ordinate of drawing point, abscissa of starting point of imgdata, ordinate of starting point of imgdata, width, height)
//             */
        });
    </script>
</head>
<body>
<div id="webcam"></div>
<input type="button" onclick=" webcam.capture (); "value =" click trigger ">"
</body>

</html>

PHP background processing

PHP drawing technology is involved in the background php.ini Open extension = PHP in_ Gd2.dll, if it’s framework development, $. Post in JS above asynchronously gives a method to the controller in framework [TP]

<?php
//$str = file_get_contents("php://input");
//file_put_contents("upload.jpg",  pack("H*", $str));
//var_dump($_POST['image']);

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']);
}
Imagepng ($IM, "circle". Time(). ". PNG"); // save and specify the path
imagedestroy($im);
// do something with $im

Source code compilation

The plug-in has a disadvantage that the pixel size cannot be adjusted. If you want to adjust the pixel size, you need to compileSRC directorySource code, I did not personally test, provide examples of successful compilationhttp://www.cnblogs.com/iasp/p…【jQuery Webcam Plugin jscam.swf Instructions for using file decompiler

Demo download

The author himself【https://github.com/infusion/j…

My own Demo:

Recommended Today

Large scale distributed storage system: Principle Analysis and architecture practice.pdf

Focus on “Java back end technology stack” Reply to “interview” for full interview information Distributed storage system, which stores data in multiple independent devices. Traditional network storage system uses centralized storage server to store all data. Storage server becomes the bottleneck of system performance and the focus of reliability and security, which can not meet […]