title: How to send an image from a Java websocket server to use in an HTML5 canvas?
body: <p>I have a WebSocket server implemented in Java. When a client connects I want to send an image over this connection for the client to use in a canvas element. I have come up with the following server code:</p>
  
  <pre><code>public void onOpen(Connection connection) {
      try {
          BufferedImage image = ImageIO.read(new File("image.jpg"));
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          ImageIO.write(image, "jpg", baos);
          byte[] byteArray = baos.toByteArray();
          connection.sendMessage(byteArray, 0, byteArray.length);
      } catch (Exception e ){
          System.out.println("Error: "+e.getMessage());
      }
  }
  </code></pre>
  
  <p>The client-side Javascript looks like this:</p>
  
  <pre><code>onmessage : function(m) {
      if (m.data) {
          if (m.data instanceof Blob) {
              var blob = m.data;
  
              var bytes = new Uint8Array(blob);
              var image = context.createImageData(canvas.width, canvas.height);
              for (var i=0; i&lt;bytes.length; i++) {
                  image.data[i] = bytes[i];
              }
          }
      }
  }
  </code></pre>
  
  <p>The connection works and the data is sent (blob.size has the correct value), but the image is not drawn onto the canvas. Firefox gives me the error message "TypeError: Value could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.".</p>
  
  <p>I am aware of the fact that this using WebSockets is not the best way to send an image to the client. After sending the image the WebSocket is only used to send text messages.</p>
  
  <p>What do I need to change for the image to be sent an applied to the canvas?</p>
  
  <p>Resources used:</p>
  
  <p><a href="https://stackoverflow.com/questions/3211156/how-to-convert-image-to-byte-array-in-java">how to convert image to byte array in java?</a></p>
  
  <p><a href="https://stackoverflow.com/questions/13390454/receive-blob-in-websocket-and-render-as-image-in-canvas">Receive Blob in WebSocket and render as image in Canvas</a></p>