Flutter 将文字转换成图片(widget转换成图片)并下载

需求

需要根据用户名字生成头像,并进行下载

依赖

用于图片下载的插件:download 1.0.0
地址:https://pub.dev/packages/download

思路

1、flutter 中 组件RepaintBoundary和RenderRepaintBoundary可用于将widget转换成图片
2、使用RepaintBoundary将组件包裹,使用RenderRepaintBoundary 进行处理,可以生成该图片的Uint8List字节数组
3、然后使用Image.memory()可将图片展示
4、使用download 插件将图片下载

代码

import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:download/download.dart';
import 'dart:ui' as ui;

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(body: PngHome()),
    );
  }
}

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

  
  State<PngHome> createState() => _PngHomeState();
}

class _PngHomeState extends State<PngHome> {
  GlobalKey globalKey = GlobalKey();
  List<Uint8List> images = [];

  void _download(Uint8List pic) {
    final stream = Stream.fromIterable(pic);
    download(stream, 'hello.png');
    print("下载");
  }

  Future<void> _capturePng() async {
    final RenderRepaintBoundary boundary =
        globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;

    if (boundary.debugNeedsPaint) {
      print("Waiting for boundary to be painted.");
      await Future.delayed(const Duration(milliseconds: 20));
      return _capturePng();
    }

    final ui.Image image = await boundary.toImage();
    final ByteData? byteData =
        await image.toByteData(format: ui.ImageByteFormat.png);
    final Uint8List pngBytes = byteData!.buffer.asUint8List();
    images.add(pngBytes);

    print(pngBytes);
    setState(() {});
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(
            child: RepaintBoundary(
              key: globalKey,
              child: Container(
                width: 150,
                height: 150,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: Colors.blue,
                    border: Border.all(width: 1, color: Colors.blue),
                    borderRadius: const BorderRadius.all(Radius.circular(75))),
                child: const Text(
                  '张三',
                  textDirection: TextDirection.ltr,
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          ),
          MaterialButton(
              onPressed: _capturePng,
              child: const Text('生成图片', textDirection: TextDirection.ltr)),
          Expanded(
            child: ListView.builder(
                itemCount: images.length,
                itemBuilder: (context, index) {
                  return Image.memory(
                    images[index],
                    width: 50,
                    height: 50,
                  );
                }),
          ),
          MaterialButton(
            onPressed: (() {
              _download(images[0]);
            }),
            child: const Text("下载"),
          )
        ],
      ),
    ));
  }
}

效果

在这里插入图片描述

在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要将图片存入文件中,可以使用Flutter提供的dart:io库中的File类。以下是一个简单的示例代码: ```dart import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; class ImageFileDemo extends StatefulWidget { @override _ImageFileDemoState createState() => _ImageFileDemoState(); } class _ImageFileDemoState extends State<ImageFileDemo> { File _imageFile; Future<void> _pickImage(ImageSource source) async { final image = await ImagePicker().getImage(source: source); setState(() { _imageFile = File(image.path); }); } Future<void> _saveImage() async { final directory = await getApplicationDocumentsDirectory(); final imagePath = '${directory.path}/image.jpg'; await _imageFile.copy(imagePath); print('Image saved to $imagePath'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Image File Demo'), ), body: Center( child: _imageFile == null ? Text('No image selected.') : Image.file(_imageFile), ), floatingActionButton: FloatingActionButton( onPressed: () => _pickImage(ImageSource.gallery), tooltip: 'Pick Image', child: Icon(Icons.add_a_photo), ), persistentFooterButtons: [ RaisedButton( onPressed: _imageFile == null ? null : _saveImage, child: Text('Save Image'), ), ], ); } } ``` 在这个示例代码中,我们使用了`ImagePicker`库来从相册中选择一张图片,并将其转换为`File`类型的对象。然后,我们使用`getApplicationDocumentsDirectory`方法获取应用程序文档目录的路径,并将图片复制到该目录下的一个特定位置。最后,我们使用`Image.file`构造函数从文件中加载图片并在屏幕上显示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值