如何使用Flutter将BASE64字符串转换为Image?

问题描述 投票:9回答:3

我正在将保存在Firebase数据库中的图像转换为Base64,并希望对其进行解码和编码。我研究了类似的问题,但我仍然遇到错误。这是我到目前为止的情况?

var image1 = String;

var pic = event.snapshot.value['image'];
var photo = BASE64.decode(pic);
image1 = photo;

我收到以下错误...

A value of type "List<int>" cannot be assigned to a variable of type "Type"

如果你能提供一个反向过程来将图像编码到Base64中,那么它们可以保存回Firebase,这将是值得赞赏的。

***更新

这是我的更新代码,仍然会抛出错误。

image1 = event.snapshot.value['image'];
var image = BASE64.decode(image1.toString());
new Image.memory(image),

错误是......

FormatException: Invalid Length must be a multiple of 4

image list base64 converter flutter
3个回答
11
投票

你可以使用Uint8List构造函数将Image转换为Flutter Image.memory小部件。 (如果需要,使用Uint8List.fromList构造函数将List转换为Uint8List。)您可以使用BASE64.encode来反过来。

这是一些示例代码。

screenshot

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData.dark(),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  String _base64;

  @override
  void initState() {
    super.initState();
    (() async {
      http.Response response = await http.get(
        'https://flutter.io/images/flutter-mark-square-100.png',
      );
      if (mounted) {
        setState(() {
          _base64 = BASE64.encode(response.bodyBytes);
        });
      }
    })();
  }

  @override
  Widget build(BuildContext context) {
    if (_base64 == null)
      return new Container();
    Uint8List bytes = BASE64.decode(_base64);
    return new Scaffold(
      appBar: new AppBar(title: new Text('Example App')),
      body: new ListTile(
        leading: new Image.memory(bytes),
        title: new Text(_base64),
      ),
    );
  }
}

但是,在数据库中存储大量二进制数据通常是个坏主意。它没有发挥Firebase实时数据库的优势,你最终会浪费带宽传输你不需要的数据以及不必要的编码和解码。您应该使用firebase_storage插件,将图像的路径或下载URL存储在数据库中。


2
投票

使用'dart:convert'包有一种更简单的方法

Image.memory(base64Decode(base64String));

实施和一些有用的方法:

import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/widgets.dart';


Image imageFromBase64String(String base64String) {
  return Image.memory(base64Decode(base64String));
}

Uint8List dataFromBase64String(String base64String) {
  return base64Decode(base64String);
}

String base64String(Uint8List data) {
  return base64Encode(data);
}

0
投票
Uint8List _bytesImage;

String _imgString = 'iVBORw0KGgoAAAANSUhEUg.....';

_bytesImage = Base64Decoder().convert(_imgString);

Image.memory(_bytesImage)
© www.soinside.com 2019 - 2024. All rights reserved.