首页 > 解决方案 > Wrong Flutter 错误 Convert image ImagePicker type File to base64, Wrong Encoded

问题描述

我需要使用 ImagePicker 转换从设备获取的图像,将其从文件类型转换为 base64 以通过数据库中的帖子存储它,但是我转换它的过程做得不好,它只转换一个细线和其余空白,显然 readAsbyte 在实现为“var bytes = imageFile.readAsBytesSync ();”时不能很好地转换 使其不完整

这就是我实施它的方式

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();

}

标签: flutterdartbase64byteencode

解决方案


从您的实施来看,

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();

的输出bytes

[255, 216, 255, 225, 1, 181, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 7, 1, 16, 0 , 2, 0, 0, 0, 26, 0, 0, 0, 98, 1, 0, 0, 4, 0, 0, 0, 1, 0, 0, 3, 192, 1, 1, 0, 4 , 0, 0, 0, 1, 0, 0, 5, 0, 1, 50, 0, 2, 0, 0, 0, 20, 0, 0, 0, 124, 1, 18, 0, 3, 0 , 0, 0, 1, 0, 1, 0, 0, 135, 105, 0, 4, 0, 0, 0, 1, 0, 0, 0, 151, 1, 15, 0, 2, 0, 0 , 0, 7, 0, 0, 0, 144, 0, 0, 0, 0, 65, 110, 100, 114, 111, 105, 100, 32, 83, 68, 75, 32, 98, 117, 105 , 108, 116, 32, 102, 111, 114, 32, 120, 56, 54, 0, 50, 48, 50, 48, 58, 48, 57, 58, 48, 50, 32, 48, 52, 58 , 49, 53, 58, 51, 54, 0, 71, 111, 111, 103, 108, 101, 0, 0, 16, 130, 157, 0, 5, 0, 0, 0, 1, 0, 0 , 1, 93, 130, 154, 0, 5, 0, 0, 0, 1, 0, 0, 1, 101, 146, 146, 0, 2, 0, 0, 0, 4, 56, 56, 57 , 0, 146, 145, 0, 2, 0, 0, 0, 4, 56, 56, 57, 0, 146, 144, 0, 2, 0, 0, 0, 4, 56, 56, 57, 0 , 146, 10, 0, 5, 0, 0, 0, 1, 0, 0, 1, 109,146, 9, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 136, 39, 0, 3, 0, 0, 0, 1, 0, 100, 0, 0, 144, 4, 0, 2, 0, 0, 0, 20, 0, 0, 1, 117, 144, 3, 0, 2, 0, 0, 0, 20, 0,

的输出imagenConvertida

/9j//+AAEEpGSUYAAQEAAAEAAQAA/9sAQwACAQEBAQECAQEBAgICAgIEAwICAgIFBAQDBAYFBgYGBQYGBgcJCAYHCQcGBggLCAkKCgoKCgYICwwLCgwJCgoK/9sAQwECAgICAgIFAwMFCgcGBwoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoK/8AAEQgFAAPAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm

反过来,我想出了以下代码:

  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();
  }

当您比较输出的值时decodedBytes

[255, 216, 255, 225, 1, 181, 69, 120, 105, 102, 0, 0, 77, 77, 0, 42, 0, 0, 0, 8, 0, 7, 1, 16, 0 , 2, 0, 0, 0, 26, 0, 0, 0, 98, 1, 0, 0, 4, 0, 0, 0, 1, 0, 0, 3, 192, 1, 1, 0, 4 , 0, 0, 0, 1, 0, 0, 5, 0, 1, 50, 0, 2, 0, 0, 0, 20, 0, 0, 0, 124, 1, 18, 0, 3, 0 , 0, 0, 1, 0, 1, 0, 0, 135, 105, 0, 4, 0, 0, 0, 1, 0, 0, 0, 151, 1, 15, 0, 2, 0, 0 , 0, 7, 0, 0, 0, 144, 0, 0, 0, 0, 65, 110, 100, 114, 111, 105, 100, 32, 83, 68, 75, 32, 98, 117, 105 , 108, 116, 32, 102, 111, 114, 32, 120, 56, 54, 0, 50, 48, 50, 48, 58, 48, 57, 58, 48, 50, 32, 48, 52, 58 , 49, 53, 58, 51, 54, 0, 71, 111, 111, 103, 108, 101, 0, 0, 16, 130, 157, 0, 5, 0, 0, 0, 1, 0, 0 , 1, 93, 130, 154, 0, 5, 0, 0, 0, 1, 0, 0, 1, 101, 146, 146, 0, 2, 0, 0, 0, 4, 56, 56, 57 , 0, 146, 145, 0, 2, 0, 0, 0, 4, 56, 56, 57, 0, 146, 144, 0, 2, 0, 0, 0, 4, 56, 56, 57, 0 , 146, 10, 0, 5, 0, 0, 0, 1, 0, 0, 1, 109,146, 9, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 136, 39, 0, 3, 0, 0, 0, 1, 0, 100, 0, 0, 144, 4, 0, 2, 0, 0, 0, 20, 0, 0, 1, 117, 144, 3, 0, 2, 0, 0, 0,

当您转换它时,它会为您提供准确的原始图像,请参见下面的示例应用程序代码:

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

在此处输入图像描述

由于解码后的图像与原始图像相同,我认为var bytes = imageFile.readAsBytesSync();工作正常。


推荐阅读