【问题标题】:Flutter, dart:io - convert Uint8List (from websocket) to a jpeg file I can drawFlutter, dart:io - 将 Uint8List(来自 websocket)转换为我可以绘制的 jpeg 文件
【发布时间】:2018-07-16 06:24:22
【问题描述】:

我编写了一个简单的nodejs ws websocket 服务器,它在客户端连接时提供二进制 jpeg 文件,如下所示:

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);
});

这段代码有错误,因为它默认以文本形式发送,所以我替换了:

webSocket.send(binaryJpegFile);

与:

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

现在我的颤振代码使用以下代码接收二进制 jpeg 文件作为 Uint8List:

  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();
  }

谁能提供关于如何将 Uint8List 转换为我可以绘制的 jpeg 文件的提示?

【问题讨论】:

    标签: flutter dart-io


    【解决方案1】:

    首先尝试将Uint8List 直接与Image.memory 小部件一起使用。

    示例:

    new Image.memory(binaryIntList);
    

    如果没有按预期工作。

    您可以使用image dart 包首先将字节解码为Image 对象,然后将其编码为您希望的格式。

    示例:

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

    然后

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

    然后将其用作

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

    希望有所帮助!

    【讨论】:

    • 太棒了!我不需要使用 _img = I.encodeIpg(_img);行。
    【解决方案2】:
    Image.memory(binaryIntList);
    

    总是有用的,祝你好运

    【讨论】:

    • 尝试添加更多信息,说明为什么要回答这个问题。仅仅一行代码是不够的。请阅读帮助中心的"How to write a good anser" 部分了解更多信息。
    猜你喜欢
    • 2021-01-28
    • 2021-07-26
    • 2022-08-18
    • 2020-07-25
    • 2020-06-15
    • 2022-10-05
    • 2023-03-10
    • 2019-05-30
    • 2020-03-06
    相关资源
    最近更新 更多