I am trying to use Jetty 8.1.2 WebSockets to send some binary data (image) to a javascript client.
websockets java code:
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 code:
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 />";
}
};
The code is good if I write an image on disk, but if I try to display the image on an HTML page, I get a random color image. I am probably encoding the image incorrectly.
Any idea how to send the image as binary data and display it using javascript?
source
share