Search code examples
javascriptjavaimagemqtt

JavaScript - Mqtt Sending and Reciving Image


I am currently working on a project in which I want to send an image as ByteArray to a mosquitto broker with java to the topic images. The subscriber of these Topic is a JavaScript application, which should convert the ByteArray,made in Java, back to an Image. The reception of the image is working well, but the image cannot be shown correctly.

What I got so far:

Java Code to Publish an Image

public void doDemo(){
        try {
            client = new MqttClient("tcp://192.168.56.1", "Camera1", new MemoryPersistence());
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            client.connect(connOpts);
            MqttMessage message = new MqttMessage();
            File imgPath = new File(Reciver.class.getResource("Card_1007330_bg_low_quality_000.png").getPath());
            BufferedImage bufferedImage = ImageIO.read(imgPath);

            // get DataBufferBytes from Raster
            WritableRaster raster = bufferedImage .getRaster();
            DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

            message.setPayload(data.getData());
            client.publish("spengergasse/building-b/2.14/images", message);

        } catch (MqttPersistenceException e) {
            e.printStackTrace();
        } catch (MqttSecurityException e) {
            e.printStackTrace();
        } catch (MqttException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                client.disconnect();
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

JavaScript to show the image

function onMessageArrived(r_message){
	console.log(r_message);
		
	document.getElementById("ItemPreview").src = "data:image/png;base64," + convert(r_message.payloadBytes);
}

function convert(buffer) {
	var binary = '';
	var bytes = new Uint8Array(buffer);
	var len = bytes.byteLength;
	for (var i = 0; i < len; i++) {
		binary += String.fromCharCode(bytes[i]);
	}
	return window.btoa(binary);
}

After Reciving the Image I am gettin this:

Page + Console

Maybe someone could help me out. Thanks a lot :D


Solution

  • Give this a try:

    function convert(buffer) {
      var decoder = new TextDecoder('utf8');
      return btoa(decoder.decode(buffer));
    }