How to convert BASE64 string into Image with Flutter?

ImageListBase64ConverterFlutter

Image Problem Overview


I'm converting images saved in my Firebase database to Base64 and would like to decode and encode. I've researched similar questions, but am still getting errors. Here is what I have so far?

var image1 = String;

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

I'm getting the following error...

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

If you could please provide a reverse process for encoding an image into Base64 so they may be saved back to Firebase, that would be appreciated.

*** UPDATE

Here is my updated code that's still throwing an error.

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

The error is...

FormatException: Invalid Length must be a multiple of 4

Image Solutions


Solution 1 - Image

There's a simpler way using 'dart:convert' package

Image.memory(base64Decode(base64String));

Implementation and some useful methods :

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);
}

Solution 2 - Image

You can convert a Uint8List to a Flutter Image widget using the Image.memory constructor. (Use the Uint8List.fromList constructor to convert a List to Uint8List if necessary.) You can use BASE64.encode to go the other way.

Here's some sample code.

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),
      ),
    );
  }
}

However, it's generally a bad idea to store large blobs of binary data in your database. It's not playing to the strengths of Firebase realtime database and you will end up wasting bandwidth transmitting data you don't need as well as unnecessary encoding and decoding. You should use the firebase_storage plugin instead, storing the path or download URL of the image in the database.

Solution 3 - Image

Uint8List _bytesImage;

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

_bytesImage = Base64Decoder().convert(_imgString);

Image.memory(_bytesImage)

Solution 4 - Image

To open a camera photo (temporary folder), editing a file and then turning it into Base64:

Code:

import 'dart:convert';
import 'package:image/image.dart' as ImageProcess;

File file = File(imagePath);
final _imageFile = ImageProcess.decodeImage(
  file.readAsBytesSync(),
);

...edit file...

String base64Image = base64Encode(ImageProcess.encodePng(_imageFile));

Decode and show:

import 'dart:convert';
import 'package:image/image.dart' as ImageProcess;

final _byteImage = Base64Decoder().convert(base64Image);
Widget image = Image.memory(_byteImage)

Solution 5 - Image

import

import 'dart:convert';
import 'dart:typed_data';

from screen load the data and assign to this variable

    Uint8List _bytes;
  _bytes = Base64Decoder().convert("iVBORw0KGgoAAAANSUhEUgAAANgAAA......");

In code tree structure widget

Image.memory(_bytes)

Solution 6 - Image

With this simple method i could set an image in flutter. The image attribute is the base64 image as string, example:

TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb2

Try the next:

Widget getImagenBase64(String imagen) {
    _imageBase64 = imagen;
    const Base64Codec base64 = Base64Codec();
    if (_imageBase64 == null) return new Container();
    bytes = base64.decode(_imageBase64);
    return Image.memory(
          bytes,
          width: 200,
          fit: BoxFit.fitWidth,
       
    );
  }

I hope this work for you. Happy coding.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharles JrView Question on Stackoverflow
Solution 1 - ImageAmir.n3tView Answer on Stackoverflow
Solution 2 - ImageCollin JacksonView Answer on Stackoverflow
Solution 3 - ImageJeferson RiveraView Answer on Stackoverflow
Solution 4 - ImageluisdemarchiView Answer on Stackoverflow
Solution 5 - Imageabhijith kView Answer on Stackoverflow
Solution 6 - ImagePedro MolinaView Answer on Stackoverflow