【问题标题】:Buffered image as JPG over Tomcat Websocket to HTML 5 Canvas将 Tomcat Websocket 上的 JPG 缓冲图像转换为 HTML 5 Canvas
【发布时间】:2013-07-01 14:05:52
【问题描述】:

嘿,我们想通过 tomcat websocket 定期将缓冲的图像发送到画布中,有点像直播。

服务器代码:

private static void broadcastImage(BufferedImage img) {     
    StreamInbound someClient;
    byte[] arr = BufferedImageToByte(img);
    ListIterator<StreamInbound> iter = clients.listIterator();
    while (iter.hasNext()) {
        someClient = (MessageInbound) iter.next();
        try {
            someClient.getWsOutbound().writeBinaryMessage(ByteBuffer.wrap(arr));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static byte[] BufferedImageToByte(BufferedImage img) {
    byte[] imageInBytes = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        baos.flush();
        imageInBytes = baos.toByteArray();
        baos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return imageInBytes;
}

问题是如何将它打包到画布中。

客户代码:

ws = new WebSocket("ws://"+ location.host + "/carduinowebdroid/websocket");
ws.binaryType = "arraybuffer";

/** stuff **/

ws.onmessage = function(message){
    if (message.data instanceof ArrayBuffer) {
        streamHandleMessage(message);
    }
}

function streamHandleMessage(message) {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');

/** what now? **/

}

非常感谢任何帮助!

【问题讨论】:

  • ofc 是 var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d');
  • 你试过用了吗:var img = new Image(); img.src = dataUrl; ctx.drawImage(img,0,0);

标签: java canvas websocket jpeg bufferedimage


【解决方案1】:

你真的需要一个 webSocket 吗? 如果没有:

var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
    can.width = img.width;
    can.height = img.height;
    ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'img.jpg';

否则看看这个: How can I create a canvas imageData array from an arrayBuffer representation of a JPG 或这个 http://www.adobe.com/devnet/html5/articles/real-time-data-exchange-in-html5-with-websockets.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2012-06-01
    相关资源
    最近更新 更多