Flutter, dart:io – convert Uint8List (from websocket) to a jpeg file I can draw

Issue

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?

Solution

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!

Answered By – Hemanth Raj

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *