0

Photos are taken with the Flutter Package image_picker and saved as variables of type "File". These images can be viewed with Flutter. From a jSON string photos in BASE64 format should be formatted into this data type in order to be able to display them. Does anyone know how this works?

It is possible to directly display BASE64 images with Flutter. The problem is that there is a "flickering" effect when rendering because the photos are reloaded each time a user types in. The framework does not seem to notice in BASE64 images that it's always the same photo. For photos in the file type, this problem does not occur.

Therefore I can not recommend rendering BASE64 strings directly. So I want to apply the conversion.

Does anyone have a solution how to convert the BASE64 string into a variable of type "File"?

    var picturesTaken = <File>[];

    Widget _showFoto(int currentFoto) {
      return Padding(
          padding: const EdgeInsets.only(bottom: 10.0),
          child: Container(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Center(
                child: Column(
                  children: <Widget>[
                    Image.file(picturesTaken[currentFoto])
                  ],
                ),
              ),
            ),
          )
      );
    }
Markus Bach
  • 763
  • 1
  • 8
  • 24

3 Answers3

0

Your base64 string shouldn't include the part 'data:image/jpg;base64,' etc. in prefix

List<int> imageBytes = _image.readAsBytesSync();
String imageB64 = base64Encode(imageBytes);

to show in ui

Image.memory(
   img,
   width: 85,
   height: 85,
   fit: BoxFit.cover,
)
Murat Aslan
  • 1,446
  • 9
  • 21
  • Thanks for the answer. In principle, that works. Unfortunately, in this variant, yo see the "flapping" effect for the user. Is there a way to convert a variable of type Uint8List to a variable of type File? – Markus Bach Jul 02 '19 at 07:22
  • @MarkusBach try this one https://stackoverflow.com/questions/50036393/how-to-convert-an-image-to-base64-image-in-flutter – Murat Aslan Jul 02 '19 at 07:42
0

Based on your answer, I found a solution:

    Image.memory(
      img,
      width: 85,
      height: 85,
      fit: BoxFit.cover,
      gaplessPlayback: true
    )  
Markus Bach
  • 763
  • 1
  • 8
  • 24
0
import 'dart:convert';
import 'dart:typed_data';

String _base64;   
Uint8List bytes = BASE64.decode(_base64);
Image.memory(bytes)

(or)

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

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

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

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

  Image.memory(base64Decode(base64String));
Lokesh
  • 357
  • 5
  • 14