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

你可能感兴趣的:(flutter,flutter)