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?
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!
Image.memory(binaryIntList);
Is always useful,good luck
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With