2019年11月7日 星期四

實現簡單的 Motion JPEG 改用 WebSocket

1. 伺服器透過 http 連線將連線資料(html 檔案), 送給客戶端
2. 客戶端收到內含 Javascript 可以開啟 WebSocket 連線的 html 檔案
3. 伺服端收到 WebSocket 升級請求, 連線後,依照時間順序,不停將 JPEG (binary)傳給客戶端.
4. 客戶端的 Javascript, 從 WebSocket 收到的 JPEG 資料, 製成 url, 將圖貼至 canvas 就可以了
放在伺服器上的 mjpeg.html 客戶端程式範例:
<html><head><meta charset='UTF-8'></head>
<body><script>
class ViewImageWS {
    constructor(width, height) {
        this._canvas = document.createElement('canvas');
        this._canvas.width  = width;
        this._canvas.height = height;
        this._canvas.style.setProperty('border', '1px solid #000000');
        this._context = this._canvas.getContext('2d');
        this._height = this._canvas.height;
        this._width  = this._canvas.width;
        document.body.append(this._canvas);
    }
    set drawImage (_img) {
        const scaley = this._height/_img.height;
        const scalex = this._width/_img.width;
        this._context.save( );
        this._context.scale(scalex, scaley);
        this._context.drawImage(_img, 0, 0, this._width, this._height);
        this._context.restore( );
    }
    set host(_ip) {
        const ws = new WebSocket(`ws://${_ip}`);
        ws.onmessage = _jpg => {// jpg binary
            const url = URL.createObjectURL(new Blob(
                [_jpg.data],
                {type: 'image/jpeg'}
            ));
            const img = new Image( );
            const release = ( )=> {
                URL.revokeObjectURL(url);
                img.remove( );
            }
            img.style= 'transform:rotate(90deg);';// rotate 90 deg if need
            img.onerror = release;
            img.onload = ( ) => {
                this.drawImage = img;
                release( );
            };
            img.src = url;
        }
    }
};
var viewer  = new ViewImageWS(1024, 768);
viewer.host = location.origin.split('//').pop( );
</script></body>
</html>

簡單 c 程式碼, 根據五行八卦相生相剋推斷吉凶

#include "stdio.h" // 五行: //               木2 //      水1           火3 //         金0     土4 // // 先天八卦 vs 五行 //                    ...