flutter 生成图片并保存到相册

1、在pubspec.yaml添加依赖

  # 图片保存
  image_gallery_saver: ^1.7.1

获取插件

flutter pub get

2、引入头文件

import 'dart:io';
import 'dart:typed_data';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:ui' as ui;

3、代码实现

  GlobalKey repaintKey = GlobalKey();

  Widget showQrCodeView() {
    return Container(
      child: Center(
        child: RepaintBoundary(
            key: repaintKey,
            child: Container(
              width: 200.px,
              height: 230.px,
              color: Colors.blue,
            )),
      ),
    );
  }


  void saveQrcodeImage() {
    Alert.showLoading();
    RenderRepaintBoundary boundary =
        repaintKey.currentContext.findRenderObject();
    boundary.toImage(pixelRatio: SizeUtil.pixelRatio).then((value) async {
      ByteData byteData =
          await value.toByteData(format: ui.ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      Permission filePermission =
          AppEnv.isIos ? Permission.photos : Permission.storage;
      var status = await filePermission.status;
      if (!status.isGranted) {
        Map<Permission, PermissionStatus> statuses =
            await [filePermission].request();
        saveQrcodeImage();
      }
      if (status.isGranted) {
        final result = await ImageGallerySaver.saveImage(pngBytes, quality: 80);
        print(result.toString());
        if (result["isSuccess"]) {
          Alert.showSuccess(message: "保存成功");
          print('图片保存 ok');
          // toast("保存成功", wring: false);
        } else {
          print('图片保存 error');
          // toast("保存失败");
        }
      }
      if (status.isDenied) {
        print("拒绝访问照片文件");
      }
    });
  }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值