0

使用vamapaull 的 Photo Booth 我正在尝试在文件夹中捕获图像。使用我的 sql 它工作正常,但将其更改为 mysqli 无法上传。网络摄像头需要捕捉但不存储图像文件夹。(在 wamp 上)。寻找幻灯片在存储图像 ID 的输出中。

 Table name  uploadimages ::   ID   Name    image   user_id 
    veiw.php
============================
<script type="text/javascript">
    hs.graphicsDir = 'graphics/';
    hs.align = 'center';
    hs.transitions = ['expand', 'crossfade'];
    hs.wrapperClassName = 'dark borderless floating-caption';
    hs.fadeInOut = true;
    hs.dimmingOpacity = .75;

    // Add the controlbar
    if (hs.addSlideshow) hs.addSlideshow({
        //slideshowGroup: 'group1',
        interval: 5000,
        repeat: false,
        useControls: true,
        fixedControls: 'fit',
        overlayOptions: {
            opacity: .6,
            position: 'bottom center',
            hideOnMouseOut: true
        }
    });
</script>
<script src="swfobject.js" language="javascript"></script>
        <script type="text/javascript">
            var flashvars = {};

            var parameters = {};
            parameters.scale = "noscale";
            parameters.wmode = "window";
            parameters.allowFullScreen = "true";
            parameters.allowScriptAccess = "always";

            var attributes = {};

            swfobject.embedSWF("take_picture.swf", "main", "700", "400", "9", 
                    "expressInstall.swf", flashvars, parameters, attributes);
        </script>

        <script type="text/javascript">
            var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
            document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
        </script>

        <script type="text/javascript">
            var pageTracker = _gat._getTracker("UA-3097820-1");
            pageTracker._trackPageview();
        </script>
        <script type="text/javascript">
    var mainswf = new SWFObject("take_picture.swf", "main", "600", "400", "9", "#ffffff");
    mainswf.addParam("scale", "noscale");
    mainswf.addParam("wmode", "window");
    mainswf.addParam("allowFullScreen", "true");
    //mainswf.addVariable("requireLogin", "false");
    mainswf.write("flashArea");

 </script>

php code

<?php
    session_start();
    //This project is done by vamapaull: http://blog.vamapaull.com/
    include_once('db.php');
    if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
        $jpg = addslashes($GLOBALS["HTTP_RAW_POST_DATA"]);
        $img = addslashes($_GET["img"]);
        //$id= $_GET["id"];
        $vid=$_SESSION['vid'];
        //$image =addslashes(file_get_contents($_FILES["img"]["tmp_name"]));
        //$image_name = addslashes($_FILES["image"]["name"]);
        $filename = "images/poza_". mktime(). ".jpg";
        file_put_contents($filename, $jpg);
        mysqli_query($db  ,"INSERT INTO uploadimages (Name,image,user_id) VALUES ('$filename','$jpg','$vid')")or die(mysqli_error($db));
        } else{
        echo "Encoded JPEG information not received.";
    }
    ?>

 -------------------------
 Other files can be seen at link given 
http://vamapaull.com/photo-booth-flash-webcam-image-capture/  This how directory looks like.image attached.

目录看起来像这样

4

1 回答 1

0

与其依赖于过时且很快就会被遗忘的技术,例如Flash您可能会考虑使用一些新的(?)HTML5 方法 - 现在 Javascript 核心中有大量的 Web api,它们使得与多媒体设备的工作相对简单并且相当不错跨浏览器支持。

以下两个脚本(可以合并为一个)应该可以让您了解如何使用所述技术完成任务 - 并且将数据保存到数据库的部分使用 a prepared statement,因此应该尽可能不存在 sql 注入的重大风险使用您的原始失败代码。

<!--
    html5_snapshot.php
    ------------------
-->
<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title>Webcam snapshots</title>
        <style>
            body{
                padding:3em;    
            }
            #media,
            #buttons,
            #results{
                box-sizing:border-box;
                width:80%;
                margin:1rem auto;
                float:none;
                text-align:center;
            }
            video,canvas{
                margin:2rem auto;
                border:1px solid black;
                border-radius:10px;
                display:inline-block;
                position:relative;
                float:none;
                clear:none;
                width:320px;
                height:240px;
            }
            h1{
                text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue;
                color: white;
                width:80%;
                margin:0 auto 0 auto!important;
                float:none;
                font: 1.5em verdana;
                text-align:center;
            }
            #results{
                font-size:0.7rem;
            }
        </style>
        <script>
            window.addEventListener('DOMContentLoaded', function(e) {
                ( function() {
                    /* edit path to suit */
                    var handler='html5_snapshot_handler.php';
                    /* establish main variables */
                    var streaming   =   false,
                      oSave         =   document.getElementById('save'),
                      oClear        =   document.getElementById('clear'),
                      oGrab         =   document.getElementById('grab'),
                      video         =   document.getElementById('video'),
                      canvas        =   document.getElementById('canvas'),
                      width = 640,
                      height = 480;

                    var basicOptions={
                        video: true,
                        audio: false
                    };
                    /* callback for previous method-no longer used
                    function gotvideo(stream){
                        if( navigator.mozGetUserMedia ) {
                            video.mozSrcObject = stream;
                        } else {
                            var vendorURL = window.URL || window.webkitURL;
                            video.src = vendorURL.createObjectURL( stream );
                        }
                        video.play();
                    }
                    */
                    function report( msg ){
                        var ctx=canvas.getContext('2d');
                            ctx.font='2em verdana';
                            ctx.fillStyle='red';
                            ctx.textAlign='center'; 
                            ctx.textBaseline='middle';
                            ctx.fillText( msg, Math.abs( canvas.width * 0.5 ), Math.abs( canvas.height * 0.5 ) );
                        console.warn( msg );
                    }
                    function setproperties(e){
                        if( !streaming ) {
                            video.width=width;
                            video.height=height;
                            canvas.width=width;
                            canvas.height=height;
                            streaming = true;
                        }
                    }
                    function takepicture(e) {
                        e.preventDefault();
                        var ctx=canvas.getContext('2d');
                            ctx.drawImage( video, 0, 0, width, height );
                    }
                    function cbsaveimage( evt ){
                        /*
                            The ajax callback function - currently only shows 
                            the returned json data but could do something 
                            much more useful
                        */
                        document.getElementById('results').innerHTML=( this.status == 200 ) ? this.response : 'error: '+this.status;    
                    }
                    function saveimage(e){
                        var el=e.target;
                        var data=canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');


                        if( !isBlankCanvas( canvas ) ){
                            var fd=new FormData();
                                fd.append( 'data', data );

                            var req = new XMLHttpRequest();
                                req.addEventListener('load', cbsaveimage, false );
                                req.open( 'POST', handler, true );
                                req.send( fd );

                        } else {
                            var bttns=[ oSave, oGrab, oClear ];

                            bttns.forEach( function(e,i,a){
                                e.disabled=true;
                            });
                            setTimeout( function(){
                                bttns.forEach( function(e,i,a){
                                    e.disabled=false;
                                });
                                canvas.getContext('2d').clearRect( 0,0, width, height );
                            },2500 );

                            report( 'Nothing to upload' );
                        }
                    }
                    function clearcanvas(evt){
                        canvas.getContext('2d').clearRect( 0,0, width, height );
                    }
                    function isBlankCanvas( canvas ) {
                        var blank=document.getElementById('empty');
                            blank.width=canvas.width;
                            blank.height=canvas.height;
                        return canvas.toDataURL() == blank.toDataURL();
                    }


                    /* Listeners */
                    oSave.addEventListener( 'click', saveimage, false );
                    oClear.addEventListener( 'click', clearcanvas, false );
                    oGrab.addEventListener( 'click', takepicture, false );
                    video.addEventListener( 'canplay', setproperties, false );

                    /*
                        navigator.getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia );
                        navigator.getMedia( basicOptions, gotvideo, report );

                        The above method is deprecated ( still works in certain browsers however )
                        but neither the above or the newer method below will work in Internet Exploder
                        The below should work in Firefox,Chrome & Opera.

                    */

                    try{
                        navigator.mediaDevices.getUserMedia( basicOptions ) .then( function( stream ) {
                            video.srcObject = stream;
                            video.onloadedmetadata = function(e) {
                                video.play();
                            };
                        }).catch( function( err ) { console.log( err.name + ": " + err.message ); } );
                    }catch( error ){
                        console.log( error );
                    }

                })();
            },false );
        </script>
    </head>
    <body>
        <h1>Webcam snapshots</h1>
        <div id='media'>
            <video id='video'></video>
            <canvas id='canvas'></canvas>
            <canvas id='empty' style='display:none' width=100 height=100></canvas>
        </div>
        <div id='buttons'>
            <input type='button' id='grab' value='Take snapshot' />
            <input type='button' id='save' value='Save Snapshot' />
            <input type='button' id='clear' value='Clear canvas' />
        </div>
        <pre id='results'></pre>
    </body>
</html>


<?php
    /*

        html5_snapshot_handler.php
        --------------------------
    */

    session_start();

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['data'] ) ) {
        /* variable to register if db call is successful or not */
        $result=false;

        /* As the image does not have a name, create a name of some sort */
        $filename=uniqid('snapshot').'_'.time().'.png';

        /* The path on the server where the upload is to be stored. */
        $uploadpath='c:/temp/fileuploads/2/';

        /* Final path for uploaded image */
        $filepath=$uploadpath . $filename;

        /* Get the file "data" */
        $data = filter_input( INPUT_POST, 'data', FILTER_SANITIZE_SPECIAL_CHARS );

        /* write to a new file */
        $bytes = file_put_contents( $filepath, base64_decode( $data ) );

        /* Save to database */
        $dbhost =   'localhost';
        $dbuser =   'root'; 
        $dbpwd  =   'xxx'; 
        $dbname =   'stack';

        $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
        $sql='insert into `uploadimages` (`name`,`image`,`user_id`) values (?,?,?);';
        $stmt=$db->prepare( $sql );
        if( $stmt ){
            $stmt->bind_param('ssi', $name, $image, $uid );
            /*
                It would be wise to store just the path to the image
                as the file is being uploaded anyway so you do not need
                to store a BLOB - over time it would take up a huge 
                amount of diskspace on the database server
            */
            $name=$filename;
            $image=$filepath;
            $uid=$_SESSION['vid'];

            $result = $stmt->execute();
            $stmt->free_result();
            $stmt->close();
            $db->close();
        }

        /* send something back to the client - callback */
        header( 'Content-Type: application/json' );
        exit( json_encode( array(
            'filename'  =>  $filename,
            'filepath'  =>  $filepath,
            'filesize'  =>  $bytes,
            'status'    =>  realpath( $filepath ) ? 1 : 0,
            'db'        =>  $result
        ) ) );
    }


    /* If the request is other than POST - report an error */
    exit( header( 'HTTP/1.1 404 Not Found', true, 404 ) );

?>

是时候承认失败了——我无法在 IE11 上使用上述内容(尽管我相信GithubwebRTC4all或Temasys WebRTC上有可用的 polyfill,但我没有尝试过这些。我相信其他地方还会有其他 polyfill .

早在 90 年代初期,当 Internet Explorer 在浏览器市场占据主导地位时,我们曾经喜欢为 IE 编写代码,并且总是发现 Netscape Navigator 抛出了各种各样的错误——尽管它现在是角色转换。

于 2017-07-19T14:54:12.813 回答