flutter中將widget轉為base64圖片
阿新 • • 發佈:2018-12-02
flutter中可以通過RepaintBoundary widget中的toImage方法將頁面中的widget轉為圖片儲存。
如何使用?
首先要在全域性定義一個global key,分配給RepaintBoundary。然後將要轉化為圖片的widget用RepaintBoundary包裹。
關鍵程式碼:
RenderRepaintBoundary boundary = _globalKey.currentContext.findRenderObject(); // 獲取頁面渲染物件
獲取到頁面渲染物件之後,就可以通過toImage方法將物件轉化為raw image data,然後通過下面三步可以將位元組資料轉化為base64字元:
ui.Image image = await boundary.toImage(pixelRatio: 3.0);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); String bs64 = base64Encode(pngBytes);
完整可執行程式碼:
import 'dart:async'; import 'dart:convert'; import'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme:new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { GlobalKey _globalKey = new GlobalKey(); Future<Uint8List> _capturePng() async { try { print('inside'); RenderRepaintBoundary boundary = _globalKey.currentContext.findRenderObject(); ui.Image image = await boundary.toImage(pixelRatio: 3.0); ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png); Uint8List pngBytes = byteData.buffer.asUint8List(); String bs64 = base64Encode(pngBytes); print(pngBytes); print(bs64); setState(() {}); return pngBytes; } catch (e) { print(e); } } @override Widget build(BuildContext context) { return RepaintBoundary( key: _globalKey, child: new Scaffold( appBar: new AppBar( title: new Text('Widget To Image demo'), ), body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( '點選下面按鈕將widget轉為圖片', ), new RaisedButton( child: Text('點我'), onPressed: _capturePng, ), ], ), ), ), ); } }