7

I've written a simple nodejs ws websocket server that is serving a binary jpeg file when a client connects as follows:

import WebSocket = require("ws");

console.log("Websocket is starting...");
// Setup websocket
const wss = new WebSocket.Server({ port: 8080 });

wss.on("connection", function connection(webSocket) {
    console.log("Connected");

    webSocket.on("message", function incoming(message) {
        console.log("received: %s", message);
    });

    webSocket.on("error", function error(err) {
        console.log(err.error);
    });
    webSocket.send(binaryJpegFile);
});

There was an error in this code as it sends as text by default so I replaced:

webSocket.send(binaryJpegFile);

with:

webSocket.send(binaryJpegFile, {binary: true});

Now my flutter codes receives the binary jpeg file as a Uint8List using the following code:

  WebSocket socket;

  void handleWebSocket(data) {
    // Listen for incoming data. We expect the data to be a JSON-encoded String.
    print("WebSocket data received");
    if (data.runtimeType == String) {
      print("String received");
      String dataString = data;
      print(dataString.length);
      print(dataString);
    } else if (data.runtimeType == Uint8List) {
      print("Binary received");
      Uint8List binaryIntList = data;
      print(binaryIntList.lengthInBytes);
    } else {
      print("Unknown datatype recieved : " + data.runtimeType.toString());
    }
  }

  connect() async {
    if (socket == null) {
      socket = await WebSocket.connect('ws://localhost:8080');
      socket.listen(handleWebSocket);
    }
    socket.add('Hello, World!');
  }

  @override
  void initState() {
    super.initState();

    connect();
  }

Can anyone give tips on how to convert Uint8List to a jpeg file I can draw?

DrZaphod
  • 502
  • 1
  • 5
  • 18

2 Answers2

10

First try using Uint8List directly with Image.memory widget.

example:

new Image.memory(binaryIntList);

If that doesn't work as expected.

You can use the image dart package to first decode the bytes to Image object and the encode it to the format you wish.

example:

import 'package:image/image.dart' as I; //So that this does not conflict with the Image widget

then

I.Image _img = I.decodeImage(binaryIntList);
_img = I.encodeJpg(_img);

then use it as

new Image.memory(_img.getBytes());

Hope that helped!

Hemanth Raj
  • 32,555
  • 10
  • 92
  • 82
1
Image.memory(binaryIntList);

Is always useful,good luck

mafanwei
  • 51
  • 4
  • 1
    Try to add more information about why this answer the question. Just a line of code is not enough. Please read the ["How to write a good anser"](https://stackoverflow.com/help/how-to-answer) section from the Help Center for more information. – guzmonne Aug 05 '19 at 02:39