簡體   English   中英

如何使用 Flutter 將 BASE64 字符串轉換為圖像?

[英]How to convert BASE64 string into the Image with Flutter?

我從數據庫中提取了一串BASE64圖像,放到屏幕上,一直報錯

String _base64 = user.data.avatar;
var image = utf8.encode(_base64);
var encoded1 = base64.encode(image);
var bytes = base64.decode(encoded1);

Image.memory(bytes,height: 70),

我收到以下錯誤...

  Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
  The following _Exception was thrown resolving an image codec:
  Exception: operation failed

如果你知道請幫助我,我真的很擔心

正如前面評論中提到的,這個問題的原因是從數據庫下載的base64 String再次被編碼為base64。 由於您已經提到您從數據庫中獲取的圖像已經編碼為 base64,因此不需要var image = utf8.encode(_base64); var encoded1 = base64.encode(image); 在你的方法中。

Base64 是一個字符串,所以不需要utf8.encode()base64.encode() 您的代碼片段應如下所示。

String _base64 = user.data.avatar;
var bytes = base64.decode(_base64);

這是一個模擬工作示例應用程序的最小再現,該應用程序顯示來自 base64 字符串的圖像。 單擊“下載”按鈕將從網絡顯示的第一張圖像保存到設備的內部存儲器。 然后應用程序將下載的圖像文件轉換為字節,然后將字節編碼為 base64 - 以模擬從數據庫中獲取的 base64 字符串。 然后使用 Image.memory(bytes) 將 base64 字符串解碼為要顯示的字節;

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @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> {
  final imageSrc = 'https://picsum.photos/250?image=9';
  var downloadPath = '';
  var downloadProgress = 0.0;
  Uint8List _imageBytesDecoded;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
                flex: 5,
                child: Row(children: [
                  // Display image from network
                  Expanded(
                      flex: 1,
                      child: Column(
                        children: [
                          Text('Image from Network'),
                          Image.network(imageSrc),
                        ],
                      )),
                  Expanded(
                    flex: 1,
                    child: Container(
                      child: Column(
                        children: [
                          Text('Image from File storage'),
                          downloadPath == ''
                              // Display a different image while downloadPath is empty
                              // downloadPath will contain an image file path on successful image download
                              ? Icon(Icons.image)
                              : Image.file(File(downloadPath)),
                        ],
                      ),
                    ),
                  ),
                ])),
            Expanded(
              flex: 1,
              child: Row(
                children: [
                  ElevatedButton(
                    // Download displayed image from imageSrc
                    onPressed: () {
                      downloadFile().catchError((onError) {
                        debugPrint('Error downloading: $onError');
                      }).then((imagePath) {
                        debugPrint('Download successful, path: $imagePath');
                        displayDownloadImage(imagePath);
                        // convert downloaded image file to memory and then base64
                        // to simulate the base64 downloaded from the database
                        base64encode(imagePath);
                      });
                    },
                    child: Text('Download'),
                  ),
                  ElevatedButton(
                    // Delete downloaded image
                    onPressed: () {
                      deleteFile().catchError((onError) {
                        debugPrint('Error deleting: $onError');
                      }).then((value) {
                        debugPrint('Delete successful');
                      });
                    },
                    child: Text('Clear'),
                  )
                ],
              ),
            ),
            LinearProgressIndicator(
              value: downloadProgress,
            ),
            Expanded(
                flex: 5,
                child: Column(
                  children: [
                    Text('Image from base64'),
                    Center(
                      child: _imageBytesDecoded != null
                          ? Image.memory(_imageBytesDecoded)
                          // Display a temporary image while _imageBytesDecoded is null
                          : Icon(Icons.image),
                    ),
                  ],
                )),
          ],
        ),
      ),
    );
  }

  displayDownloadImage(String path) {
    setState(() {
      downloadPath = path;
    });
  }

  // Convert downloaded image file to memory and then base64
  // to simulate the base64 downloaded from the database
  base64encode(String imagePath) async {
    var imageBytes = File(imagePath).readAsBytesSync();
    debugPrint('imageBytes: $imageBytes');
    // This simulates the base64 downloaded from the database
    var encodedImage = base64.encode(imageBytes);
    debugPrint('base64: $encodedImage');
    setState(() {
      _imageBytesDecoded = base64.decode(encodedImage);
      debugPrint('imageBytes: $_imageBytesDecoded');
    });
  }

  Future deleteFile() async {
    final dir = await getApplicationDocumentsDirectory();
    var file = File('${dir.path}/image.jpg');
    await file.delete();
    setState(() {
      // Clear downloadPath and _imageBytesDecoded on file deletion
      downloadPath = '';
      _imageBytesDecoded = null;
    });
  }

  Future downloadFile() async {
    Dio dio = Dio();
    var dir = await getApplicationDocumentsDirectory();
    var imageDownloadPath = '${dir.path}/image.jpg';
    await dio.download(imageSrc, imageDownloadPath,
        onReceiveProgress: (received, total) {
      var progress = (received / total) * 100;
      debugPrint('Rec: $received , Total: $total, $progress%');
      setState(() {
        downloadProgress = received.toDouble() / total.toDouble();
      });
    });
    // downloadFile function returns path where image has been downloaded
    return imageDownloadPath;
  }
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM