0

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

3
  • imageBytes are wrong, you need encodeJpg instead (or any other encode* method) Commented Mar 13, 2020 at 8:04
  • stackoverflow.com/questions/50036393/… Commented Mar 13, 2020 at 8:06
  • i mean base64Encode works correctly - this is imageBytes that are wrong Commented Mar 13, 2020 at 8:13

2 Answers 2

4

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),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your reply! for List<int> imageBytes = imageResized.readAsBytesSync(); it says that value String cant be assigned to variable List<int>
Oh my fault, sorry, misspelled something on my end
Glad to help. please mark this as answer if it help you. thanks.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.