Joe Smirth
Joe Smirth

Reputation: 19

converting image to base64 in flutter

I take a picture with phone's camera, then resize it and convert it to base64 string. However, after those manipulations, base64 string that I get doesn't seem to be valid. I try to convert it back to image on this website https://codebeautify.org/base64-to-image-converter . After I click generate image, nothing happens, however sample on their website works. Tried on the other websites and still no luck. My code:

import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker.dart';

  File _photo;
  String photoBase64;

  Future getImage(ImageSource source) async {
    var photo = await ImagePicker.pickImage(source: source);

    img.Image image = img.decodeImage(photo.readAsBytesSync());
    img.Image imageResized = img.copyResize(image, width: 120);

    setState(() {
      _photo = photo;

    List<int> imageBytes = imageResized.getBytes();
    photoBase64 = base64Encode(imageBytes);
    });
  } 

I tried base64UrlEncode() too, however the issue still remains. String I am trying to convert back to image is photoBase64. My goal is to send it in a body of a POST request later. What exactly am I doing wrong here?

Thank you

Upvotes: 0

Views: 7766

Answers (2)

Husnul Aqib
Husnul Aqib

Reputation: 1

my solution

  Future getImage() async {
    pickedFile =
        await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);
    setState(() {
      if (pickedFile != null) {
        file = File(pickedFile!.path); 
        final bytes =
            file!.readAsBytesSync(); 
        img64 = base64Encode(bytes);
      } else {
        print('No image selected.');
      }
    });
  }

Upvotes: 0

chunhunghan
chunhunghan

Reputation: 54365

You can copy paste run full code below
You can use package https://pub.dev/packages/flutter_native_image to get resized image

imageResized = await FlutterNativeImage.compressImage(photo.path,
    quality: 100, targetWidth: 120, targetHeight: 120);
...
List<int> imageBytes = imageResized.readAsBytesSync();

working demo

enter image description here enter image description here enter image description here

full code

import 'package:flutter/material.dart';
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'dart:convert';
import 'package:flutter_native_image/flutter_native_image.dart';

void main() => runApp(MyApp());

File _photo;
String photoBase64;

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  File imageResized;

  Future getImage(ImageSource source) async {
    var photo = await ImagePicker.pickImage(source: source);

    imageResized = await FlutterNativeImage.compressImage(photo.path,
        quality: 100, targetWidth: 120, targetHeight: 120);

    setState(() {
      _photo = photo;

      List<int> imageBytes = imageResized.readAsBytesSync();
      photoBase64 = base64Encode(imageBytes);
      print(photoBase64);
    });
  }

  void _incrementCounter() {
    getImage(ImageSource.camera);
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            imageResized == null ? Container() : Image.file(imageResized),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Upvotes: 4

Related Questions