flutter 生成图片并保存到相册

flutter 生成图片并保存到相册,第1张

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 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("拒绝访问照片文件");
      }
    });
  }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/994068.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存