0

最終年度のプロジェクトの一環として Intel Galileo Gen 2 で Node.js を実行しています。Galileo を使用して Web カメラを使用して写真を撮り、キャンバス要素を使用して毎回撮影した写真を Web ページに提供しようとしています。

これは Node.js サーバー上のコードです。

    // this 'message' event receives the sketch datagram 
server.on("message", function (msg, rinfo) { 
    udp_msg = msg.toString();     
    if(udp_msg == "picTaken") {
                    fs.readFile(__dirname + '/pictures/pic'+picNum+'.jpg', function(err, buf){

                    io.emit('image', { image: true, buffer:         buf.toString('base64') });
                    console.log('image file is initialized' + picNum);
                    picNum++;
                });
    }
    //console.log("from " + rinfo.address + " message:" + udp_msg);     
    // just bypassing the message sent by the sketch     
    io.emit("server-event-info", udp_msg);
});

galileo で実行されているスケッチは、文字列「picTaken」をサーバーに送信します。これにより、この関数が呼び出されます。これは、画像を表示するための HTML ページのコードです。

<div class="pic">
        <canvas id="img"  width="280" height="220" style="border:1px solid #000000;">
            Your browser does not support the HTML5 canvas tag.
        </canvas>
    </div> 
    <script>
        var ctx = document.getElementById('img').getContext('2d');
        socket.on("image", function(info) {
          if (info.image) {
            var img = new Image();
            img.src = 'data:image/jpeg;base64,' + info.buffer; 
            ctx.drawImage(img, 0, 0);
            console.log("Image received");
          }
        });
    </script>

問題は、「受信した画像」をコンソールに出力しているのに表示されないため、画像がブラウザによって受信されたように見えることです。行を置き換えるなどして、画像を静的に表示しようとすると機能します

  fs.readFile(__dirname + '/pictures/pic'+picNum+'.jpg', function(err, buf){

fs.readFile(__dirname + '/pictures/pic1.jpg', function(err, buf){

だから何が問題なのかわからない

4

1 に答える 1

2

クライアントが画像を受信して​​いることが問題であることがわかりましたが、表示しようとする前に画像が読み込まれるのを待っていませんでした。クライアント側のコードを変更して、画像が読み込まれるのを待ってから画像を表示すると、うまくいきました。クライアント側のコードは次のとおりです。

var ctx = document.getElementById('img').getContext('2d');
    socket.on("image", function(info) {
      if (info.image) {
        var img = new Image();
        img.onload = function () {
            ctx.drawImage(img, 0, 0);
        };
        img.src = 'data:image/jpg;base64,' + info.buffer;   
        console.log("Image received");
      }
    });
于 2016-04-22T19:16:38.237 に答える