编程语言
首页 > 编程语言> > java – jetty websockets发送二进制数据(图像)

java – jetty websockets发送二进制数据(图像)

作者:互联网

我正在尝试使用Jetty 8.1.2 WebSockets将一些二进制数据(图像)发送到javascript客户端.

websockets java代码:

BufferedImage image = getTheImage();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
baos.flush();
byte[] imageInBytes = baos.toByteArray();
baos.close();

socket.getConnection().sendMessage(imageInBytes, 0, imageInBytes.length);

javascript代码:

binarySocket.onmessage = function(event) {
if (event.data instanceof ArrayBuffer) {
    var bytearray = new Uint8Array(event.data);

    var tempcanvas = document.createElement('canvas');
    tempcanvas.height = imageheight;
    tempcanvas.width = imagewidth;
    var tempcontext = tempcanvas.getContext('2d');

    var imgdata = tempcontext.getImageData(0, 0, imagewidth,imageheight);
    var imgdatalen = imgdata.data.length;

    for ( var i = 8; i < imgdatalen; i++) {
        imgdata.data[i] = bytearray[i];
    }

    tempcontext.putImageData(imgdata, 0, 0);

    var img = document.createElement('img');
    img.height = imageheight;
    img.width = imagewidth;
    img.src = tempcanvas.toDataURL();
    chatdiv = document.getElementById('chatdiv');
    chatdiv.appendChild(img);
    chatdiv.innerHTML = chatdiv.innerHTML + "<br />";
}

};

如果我在磁盘上写图像代码很好,但如果我尝试在HTML页面上显示图像,我会得到一些随机的彩色图像.
我可能以错误的方式编码图像.

知道如何将图像作为二进制数据发送并用javascript显示吗?

解决方法:

你是对的.问题是图像编码.

更换:

img.src = tempcanvas.toDataURL();

img.src = tempcanvas.toDataURL("image/jpeg");

默认格式为PNG.

标签:java,javascript,websocket,binary-data,jetty
来源: https://codeday.me/bug/20190520/1143047.html