Anu
Anu

Reputation: 630

how to convert image to byte and again convert it to image in flutter?

I am trying to use the image_picker plugin. I can get the image as file using this plugin. I need to convert this image to bytes and send to a api. So I tried to use dart:convert to convert the image to byte string. Now when I decode I am getting a Uint8List type. How to convert this to a file and display in a Image.file(). I couldn’t proceed from here. Can someone help me with this.

consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget

This is the code I tried so far.

var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      imageURI = image;
      final bytes = image.readAsBytesSync();

      String img64 = base64Encode(bytes);
      print(bytes);
      print(img64);

      final decodedBytes = base64Decode(img64);
      print(decodedBytes);
      //consider i am getting this decodedBytes i am getting from a api response, how can i convert them to display in a Image widget 
    });

I am getting this error using writeAsBytesSync(),

Unhandled Exception: FileSystemException: Cannot open file, path = 'decodedimg.png'

Upvotes: 5

Views: 16019

Answers (1)

Herbert Poul
Herbert Poul

Reputation: 4893

You get this error, because you can't write to any arbitrary location in an application sandbox. You can use path_provider to look up a temporary directory.

But in your case, just use the image object, pickImage already returns a File object, so just use Image.file(image)

If you want to decode a base64 into a temporary directory you can use:

import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

Future<File> writeImageTemp(String base64Image, String imageName) async {
  final dir = await getTemporaryDirectory();
  await dir.create(recursive: true);
  final tempFile = File(path.join(dir.path, imageName));
  await tempFile.writeAsBytes(base64.decode(base64Image));
  return tempFile;
}

with pubspec.yaml:

dependencies:
  path: ^1.6.0
  path_provider: ^1.6.7

Upvotes: 1

Related Questions