首页 > 解决方案 > 来自相机颤动的base64encode图像

问题描述

我正在尝试将图像编码为 base64 以发送到服务器。我从图像中获取的 base 64 字符串无效。

我可以显示从相机拍摄的图像。它没有正确编码为base64。

File img;
 void getPic() async {
    img = await ImagePicker.pickImage(source: ImageSource.camera);
    if (img != null) {
      print(img);
      List<int> imageBytes = await img.readAsBytes();
      base64Image =  base64Encode(imageBytes);
      print(base64Image);
      setState(() => base64Image);
    }
  }

标签: dartflutter

解决方案


你也可以在这里查看我的答案

场景:图像未正确解码。

File imageFile;

void _openGallery(BuildContext context) async{ 
  var picture = await ImagePicker().getImage(source: ImageSource.gallery);
  this.setState(() {
    imageFile = File(picture.path);
    var bytes = imageFile.readAsBytesSync();
  
    String imagenConvertida = base64.encode(bytes);
    print(bytes);
    print(imagenConvertida);

});
Navigator.of(context).pop();

这就是我将其转换Uint8List为 FlutterImage小部件的方式:

      File imageFile;
      Image decodedImage;
    
      void _openGallery(BuildContext context) async {
        var picture = await ImagePicker().getImage(source: ImageSource.gallery);
        this.setState(
          () {
            imageFile = File(picture.path);
            // Convert image to base64
            var bytes = imageFile.readAsBytesSync();
            String imagenConvertida = base64.encode(bytes);
            print('Value of bytes: $bytes');
            print('Value of imagenConvertida: $imagenConvertida');
            // Convert base64 to image
            Uint8List decodedBytes = base64.decode(imagenConvertida);
            decodedImage = Image.memory(decodedBytes);
            print('Value of decodedBytes: $decodedBytes');
            print('Value of decodedImage: $decodedImage');
          },
        );
        // Commented out for testing purposes
        // Navigator.of(context).pop();
      }

例如,这是一个检查图像是否正确转换的基本实现:

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      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> {
  // From SO
  File imageFile;
  Image decodedImage;

  void _openGallery(BuildContext context) async {
    var picture = await ImagePicker().getImage(source: ImageSource.gallery);
    this.setState(
      () {
        imageFile = File(picture.path);
        // Convert image to base64
        var bytes = imageFile.readAsBytesSync();
        String imagenConvertida = base64.encode(bytes);
        print('Value of bytes: $bytes');
        print('Value of imagenConvertida: $imagenConvertida');
        // Convert base64 to image
        Uint8List decodedBytes = base64.decode(imagenConvertida);
        decodedImage = Image.memory(decodedBytes);
        print('Value of decodedBytes: $decodedBytes');
        print('Value of decodedImage: $decodedImage');
      },
    );
    // Commented out for testing purposes
    // Navigator.of(context).pop();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: 20.0,
            ),
            Text('Original image from gallery'),
            SizedBox(height: 10.0),
            Container(
              color: Colors.blueGrey,
              height: 200.0,
              width: 150.0,
              child: imageFile == null
                  ? Text('Image is not loaded')
                  : Image.file(imageFile),
            ),
            SizedBox(height: 20.0),
            Text('Image decoded from base64'),
            SizedBox(height: 10.0),
            Container(
              color: Colors.grey,
              height: 200.0,
              width: 150.0,
              child: decodedImage == null
                  ? Text('Image is not loaded')
                  : decodedImage,
            ),
          ],
        ),
      ),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        // crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () {
              // _getImage();
              _openGallery(context);
              print('Open Gallery');
            },
            tooltip: 'Pick an image',
            child: Icon(Icons.image),
          ),
          SizedBox(
            width: 20,
          ),
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

在此处输入图像描述


推荐阅读