欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

android 生成推广图片保存_flutter 如何生成图片并保存到手机相册?

发布时间:2023/12/31 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 android 生成推广图片保存_flutter 如何生成图片并保存到手机相册? 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

No matter what he does, every personon earth plays a central role in the historyof the world. And normally he doesn't know it.  —— Paulo Coelho, The Alchemist

在pubspec.yaml文件添加插件

  • image_gallery_saver安装1.5.0版本就好了,我之前安装的1.6.6会报错
  # 权限控制插件
  permission_handler: 5.0.1
  permission_handler_platform_interface: ^2.0.1
  # 文件保存插件
  image_gallery_saver: 1.5.0
  • 记得安装一下
flutter pub get

android和ios配置

ios 修改文件

  • 在ios/Runner/Info.plist添加以下代码
 NSPhotoLibraryUsageDescription
  
    NSPhotoLibraryAddUsageDescription
    请允许APP保存图片到相册

android 修改文件

  • 在android/app/src/main/AndroidManifest.xml添加以下代码
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

将需要生成图片的组件用RepaintBoundary包裹

GlobalKey globalKey = GlobalKey();
RepaintBoundary(
      key: globalKey,
      child:Text('我要生成图片'),
      )

保存图片到相册

在点击事件里调用这个方法就可以了

 /// 保存图片
  static Future<void> saveImage(GlobalKey globalKey) async {
    RenderRepaintBoundary boundary =
    globalKey.currentContext.findRenderObject();
    var image = await boundary.toImage(pixelRatio: 6.0);
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    // final result = await ImageGallerySaver.saveImage(pngBytes,
    //     quality: 60, name: "hello");
    // if (result) {
    //   print('ok');
    //   // toast("保存成功", wring: false);
    // } else {
    //   print('error');
    // }

    if (Platform.isIOS) {
      var status = await Permission.photos.status;
      if (status.isUndetermined) {
        Map statuses = await [
          Permission.photos,
        ].request();
        saveImage(globalKey);
      }if (status.isGranted) {final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 60, name: "hello");if (result) {
          print('ok');// toast("保存成功", wring: false);
        } else {
          print('error');// toast("保存失败");
        }
      }if (status.isDenied) {
        print("IOS拒绝");
      }
    } else if (Platform.isAndroid) {var status = await Permission.storage.status;if (status.isUndetermined) {
        Map statuses = await [
          Permission.storage,
        ].request();
        saveImage(globalKey);
      }if (status.isGranted) {
        print("Android已授权");final result = await ImageGallerySaver.saveImage(pngBytes, quality: 60);if (result != null) {
          print('ok');// toast("保存成功", wring: false);
        } else {
          print('error');// toast("保存失败");
        }
      }if (status.isDenied) {
        print("Android拒绝");
      }
    }
  }

完整demo代码

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:interviewer_app/common/component_index.dart';
// 一定要引入这三个插件
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
import 'package:permission_handler/permission_handler.dart';

import 'package:flutter/services.dart';
import 'dart:ui' as ui;
import 'dart:typed_data';
import 'dart:io';

class ShareJob extends StatefulWidget {
  const ShareJob({Key key, this.searchKey}) : super(key: key);
  final String searchKey;


  @override
  State createState() {

    return new _ShareJobState();
  }
}

class _ShareJobState extends State<ShareJob> {
// globalKey 在这里设置
  GlobalKey globalKey = GlobalKey();
  Uint8List newPngBytes;

  Widget shareImage() {
    return
      RepaintBoundary(
      key: globalKey,
      child:
      Container(

        child:
        // 图片
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Color(0xFF5B9AFF),
                boxShadow:[
                BoxShadow(
                    color: Color(0x1A000000),
                    offset: Offset(0, 5.0),
                    blurRadius: 24.0
                ),
                  ]),

              width: MediaQuery.of(context).size.width * 0.6,

              child:
              Column(
                children: [
                  Gaps.vGap25,
                  Text('热招职位', style: TextStyle(fontSize: 22, color: Colors.white, fontWeight: FontWeight.w300),),
                  Gaps.vGap25,
                  Container(
                    margin: EdgeInsets.only(bottom: 22,left: 15,right: 15),
                    // padding: EdgeInsets.only(bottom: 22,left: 15,right: 15),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10.0),
                        boxShadow:[
                          BoxShadow(
                              color: Color(0x1A000000),
                              offset: Offset(0, 5.0),
                              blurRadius: 24.0
                          ),
                        ]),
                    // padding: EdgeInsets.all(10),
                    // margin: EdgeInsets.only(bottom: 6),
                    // width: MediaQuery.of(context).size.width * 0.6,
                    // height: 305,
                    child: Column(
                      children: [
                        Gaps.vGap25,
                        Gaps.vGap10,
                        Text('测试工程师', style: TextStyle(fontSize: 15, color: Color(0xFF313753), fontWeight: FontWeight.w500),),
                        Gaps.vGap10,
                        Text('15k-20K | 上海', style: TextStyle(fontSize: 15, color: Color(0xFFF4A25A), fontWeight: FontWeight.w500),),
                        Gaps.vGap10,
                        Text('公司名', style: TextStyle(fontSize: 10, color: Color(0xFF313753), fontWeight: FontWeight.w400),),
                        Gaps.vGap15,
                        Image.asset(Utils.getImgPath('checked'),
                            width: 115.0),
                        Gaps.vGap25,
                        Text('长按查看职位详情', style: TextStyle(fontSize: 9, color: Color(0xFF313753), fontWeight: FontWeight.w400),),
                        Gaps.vGap25,
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),

      )
    );
  }

  /// 保存图片
  static Future<void> saveImage(GlobalKey globalKey) async {
    RenderRepaintBoundary boundary =
    globalKey.currentContext.findRenderObject();
    var image = await boundary.toImage(pixelRatio: 6.0);
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    // final result = await ImageGallerySaver.saveImage(pngBytes,
    //     quality: 60, name: "hello");
    // if (result) {
    //   print('ok');
    //   // toast("保存成功", wring: false);
    // } else {
    //   print('error');
    // }

    if (Platform.isIOS) {
      var status = await Permission.photos.status;
      if (status.isUndetermined) {
        Map statuses = await [
          Permission.photos,
        ].request();
        saveImage(globalKey);
      }if (status.isGranted) {final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 60, name: "hello");if (result) {
          print('ok');// toast("保存成功", wring: false);
        } else {
          print('error');// toast("保存失败");
        }
      }if (status.isDenied) {
        print("IOS拒绝");
      }
    } else if (Platform.isAndroid) {var status = await Permission.storage.status;if (status.isUndetermined) {
        Map statuses = await [
          Permission.storage,
        ].request();
        saveImage(globalKey);
      }if (status.isGranted) {
        print("Android已授权");final result = await ImageGallerySaver.saveImage(pngBytes, quality: 60);if (result != null) {
          print('ok');// toast("保存成功", wring: false);
        } else {
          print('error');// toast("保存失败");
        }
      }if (status.isDenied) {
        print("Android拒绝");
      }
    }
  }@overrideWidget build(BuildContext context) {return new Scaffold(
      appBar: AppBar(title: Text('分享职位'), titleSpacing: 0, centerTitle: true),
      body: SingleChildScrollView(
        child: Container(
          child: Column(children: [
            Gaps.vGap25,
            Row(
              children: [// http://images.shejidaren.com/wp-content/uploads/2020/03/36365-4.png// IconButton(//   iconSize: 22,//   icon: const Icon(Icons.close),//   onPressed: (){//   },// )
                Gaps.hGap30,
                Gaps.hGap10,
                Gaps.hGap10,
                Column(
                  children: [
                    Container(
                      decoration: new BoxDecoration(
                        color: Cor.roundbg_1,
                        borderRadius: BorderRadius.circular(100),
                      ),
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.only(bottom: 6),
                      width: 60,
                      height: 60,
                      child: Image.network('http://images.shejidaren.com/wp-content/uploads/2020/03/36365-4.png'),
                    ),
                    Text('微信好友',
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Cor.black_1, fontSize: 14),
                    )
                  ],
                ),
                Gaps.hGap30,
                Gaps.hGap10,
                Gaps.hGap10,
                Column(
                  children: [
                    Container(
                      decoration: new BoxDecoration(
                        color: Cor.roundbg_1,
                        borderRadius: BorderRadius.circular(100),
                      ),
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.only(bottom: 6),
                      width: 60,
                      height: 60,
                      child: Image.network('https://www.sj520.cn/sc/ima/weixin_sj520_11.jpg'),
                    ),
                    Text('朋友圈',
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Cor.black_1, fontSize: 14),
                    )
                  ],
                ),
              ],
            ),
            Gaps.vGap20,// 灰色横线
            Container(
              decoration: new BoxDecoration(color: Cor.roundbg_1),
              width: double.infinity,
              height: 10,
            ),
            Gaps.vGap15,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Text('已生成朋友圈图片',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Cor.black_1.withOpacity(0.65), fontSize: 14),
                ),
              ],
            ),
            Gaps.vGap15,
            shareImage(),
            Gaps.vGap15,
            Gaps.vGap10,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                RaisedButton(
                    color: Cor.blue_1,
                    highlightColor: Colors.blue[100],
                    colorBrightness: Brightness.dark,
                    splashColor: Cor.blue_2,
                    padding: EdgeInsets.only(left: 34,right: 34),
                    child: Text("保存至相册",
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0)),
                    onPressed: () async {
                      print('------');
                      print(globalKey.currentContext);// createImageFromRepaintBoundary(globalKey);// final g = createImageFromWidget(saveImage());// print(g);
                      saveImage(globalKey);
                    },
                    ),
              ],
            ),
            Gaps.vGap25,
            Gaps.vGap25,
          ]),
        ),
      ),
    );
  }
}

效果图

效果图

保存成功后可以在模拟器相册看到

模拟器相册

我们每一个人不管做什么,都在整个世界的历史长河中扮演着很重要的角色,只是通常我们自己并不知道。—— JPaulo Coelho, The Alchemist

- END -▼往期精彩回顾▼js怎么点击复制链接并且选中文本手把手教你如何发布系统和GitHub的oAuth登录EventLoop面试必考,你完全会了么?Chrome调试技巧系列三Chrome调试技巧系列二Chrome的骚操作系列(一)JS预编译JavaScript 浮点数之迷:大数危机JavaScript 浮点数之迷:0.1 + 0.2 为什么不等于 0.3?扫码关注你点的每个赞,我都认真当成了喜欢

总结

以上是生活随笔为你收集整理的android 生成推广图片保存_flutter 如何生成图片并保存到手机相册?的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。