Flutter:从 Byte Buffer/Int8List 渲染图像

在 Flutter 中,您可以使用Image.memory构造函数从字节的Int8List渲染图像,如下所示:****

Image.memory(Uint8List.fromList(myBytes));

如果您拥有的是字节缓冲区,请使用:

Image.memory(Uint8List.fromList(myBuffer.asInt8List()));

例子

此示例执行以下操作:

  1. 从图像的给定 URL 读取字节数据(您可以更改此步骤以适应您的情况,例如从文件或数据库中获取字节数据)
  2. 使用Image.memory从字节数据中渲染图像

这个例子的目的是演示我之前提到的。实际上,我们要构建的微型应用程序没有多大意义,因为我们可以直接显示带有 URL 的图像,而不是绕道从 URL 中获取其字节,然后使用这个字节列表来显示图像.

截屏:

Flutter:从 Byte Buffer/Int8List 渲染图像

完整代码:

// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:typed_data';

void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  // this byte data will be used to render the image
  Int8List? _bytes;

  // get byte data from an image url
  void _getBytes(imageUrl) async {
    final ByteData data =
        await NetworkAssetBundle(Uri.parse(imageUrl)).load(imageUrl);
    setState(() {
      _bytes = data.buffer.asInt8List();

      // see how byte date of the image looks like
      print(_bytes);
    });
  }

  @override
  void initState() {
    // call the _getBytes() function
    _getBytes(
        'https://www.kindacode.com/wp-content/uploads/2022/07/KindaCode.jpg');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('KindaCode.com')),
      body: Center(
          child: _bytes == null
              ? const CircularProgressIndicator()
              : Image.memory(
                  Uint8List.fromList(_bytes!),
                  width: 340,
                  height: 260,
                  fit: BoxFit.cover,
                )),
    );
  }
}