首页 文章

如何在flutter中使用rootBundle来加载图像?

提问于
浏览
1

我使用图像插件( image: ^2.0.4 ),所以我可以在图像上写一些内容,然后将新图像保存到设备或通过邮件发送 . 我尝试使用“ new File ”加载图像,但在Flutter上出错 . 我问并搜索并得到一个提示,我可以使用rootBundle在Flutter中加载图像 . 我做了,我得到了以下错误 .

[错误:topaz / lib / tonic / logging / dart_error.cc(16)]未处理的异常:无法加载资产:packages / myAppName / assets / images / ReceiptRaw_1.jpg

该插件在我创建一个简单的dart控制台应用程序时有效,但无法使用flutter加载 . 请帮忙,

This is the Flutter Code:

Future<bool> makeReceiptImage() async {

// UPDATE ****************************************

      // load the receipt jpeg
  var imageData = await rootBundle.load('packages/myAppName/dekonts/ReceiptRaw_1.jpg');
  print("imageData: $imageData"); // Prints as imageData: Instance of 
'_ByteDataView'

// UPDATE ****************************************

  Image _receiptImage = await decodeImage(new File(imageData).readAsBytesSync());

      drawString(_receiptImage, arial_48, 440, 30, “Customer Name”, color: 0xFF000000); 

      // Write it to disk as a different jpeg 
      var new_jpeg = await encodeJpg(_receiptImage); 
      String newImagePath = await rootBundle.loadString('packages/myAppName/assets/images/ReceiptRaw_2.jpg'); 
      await new File(‘$newImagePath’).writeAsBytesSync(new_jpeg); 
    }

This is the Dart Console Code:

import 'dart:io';
import 'dart:convert';
import 'dart:async';
import 'package:image/image.dart';

void main() async {
  // load the receipt jpeg
  String mImagePath = 'images/ReceiptRaw_1.jpg';
  Image _receiptImage = decodeImage(new File(mImagePath).readAsBytesSync());
  drawString(_receiptImage, arial_48, 440, 30, “Customer Name”, color: 0xFF000000);

  // Write it to disk as a different jpeg
  var new_jpeg = encodeJpg(_receiptImage);
  new File('images/ReceiptRaw_1.jpg').writeAsBytesSync(new_jpeg);
}

Update-1: 当我使用下面的代码时,我得到错误:

在pubspec.yaml中检测到错误:找不到资产的文件或变体:packages / myAppName / assets / images / ReceiptRaw_1.jpg

String imageData = await rootBundle.loadString('packages/myAppName/assets/images/ReceiptRaw_1.jpg');
  Image _receiptImage = await decodeImage(new File(imageData).readAsBytesSync());

Update-2: 如果我使用 rootBundle.load 我收到以下错误 .

错误:'dart.typed_data :: ByteData'类型的值不能分配给'dart.core :: String'类型的变量 .

var imageData = await rootBundle.load('packages/myAppName/assets/images/ReceiptRaw_1.jpg');
  Image _receiptImage = await decodeImage(new File(imageData).readAsBytesSync());

New Update:

Step 1: 移至 ReceiptRaw_1.jpg 进入 lib/dekonts/ 文件夹

Change to:

assets:
  - packages/myAppName/dekonts/ReceiptRaw_1.jpg

Change to:

var imageData = await rootBundle.load('packages/myAppName/dekonts/ReceiptRaw_1.jpg');
print("imageData: $imageData");

Result: 打印为

imageData:'_ByteDataView'的实例

Step 2: Move to /lib/assets/images/ReceiptRaw_1.jpg 文件夹

Change to:

assets:
  - packages/myAppName/lib/assets/images/ReceiptRaw_1.jpg

Change to:

var imageData = await rootBundle.load('packages/myAppName/lib/assets/images/ReceiptRaw_1.jpg');
print("imageData: $imageData");

Result: 收到错误:

解决依赖关系...运行'gradlew assembleDebug'...在pubspec.yaml中检测到错误:找不到资产的文件或变体:packages / myAppName / lib / assets / images / ReceiptRaw_1.jpg

更新:

///要包括,比如第一张图片,应用程序的pubspec.yaml应///在资产部分中指定它:/// /// assets:/// - packages / fancy_backgrounds / backgrounds / background1 . png /// ///暗示了lib /,因此它不应包含在资产路径中 .

2 回答

  • 1

    pub依赖项的文件不可用作文件 . 它们包含在存档文件中 .

    将图像添加到 pubspec.yaml 中的资源

    flutter:
      assets:
        - packages/myAppName/assets/images/ReceiptRaw_1.jpg
    

    然后加载它

    var imageData = await rootBundle.load('packages/myAppName/assets/images/ReceiptRaw_1.jpg');
    

    为此,文件 ReceiptRaw_1.jpg 需要进入

    myAppName/lib/assets/images/ReceiptRaw_1.jpg
    

    lib/ 部分是强制性的 .

  • 1

    在@GünterZöchbauer的帮助下,我终于成功了 . 我对Stack Overflow成员的贡献很小 .

    // TODO: 1 - LOAD EVERYTHING

    Future _loadEverything() async {
        await _requestAppDocumentsDirectory();   // TODO: 2 - GET APP DOCUMENTS DIRECTORY
        _dekontExist = await makeReceiptImage(); // TODO: 3 - MAKE A RECEIPT
    
        // Show the writen image
        if (_dekontExist == true) {
          setState(() {
            newDekontImage = _appDocumentsDirectory + "/" + widget._currentUserReceiptNo + ".jpg";
            imageOkay = true; // FOR - 4 - MAIN WIDGET BUILD
          });
        }
      }
    

    // TODO: 2 - GET APP DOCUMENTS DIRECTORY

    Future _requestAppDocumentsDirectory() async {
      // I choose temp dir because I don’t want to write twice same Receipt
      // Also when user close the app it will destroys the images
      final _directory =
          await getTemporaryDirectory(); //getApplicationDocumentsDirectory();
      setState(() {
        _appDocumentsDirectory = _directory.path;
      });
    }
    

    // TODO: 3 - MAKE A RECEIPT

    Future<bool> makeReceiptImage() async {
    
      // I use this as a template:
      // 'packages/mayApp/assets/images/CapitalReceipt.jpg'  
    
      ByteData imageData = await rootBundle.load('packages/mayApp/assets/images/CapitalReceipt.jpg');
      List<int> bytes = Uint8List.view(imageData.buffer);
      Image _receiptImage = decodeImage(bytes);
    
      // TODO: WRITE ON TO THE IMAGE
      drawString(_receiptImage, arial_48, 440, 30, “Customer Receipt - Customer Name”, color: 0xFF000000);
    
    
      // Write it to disk as a different jpeg
        var new_jpeg = await encodeJpg(_receiptImage);
        String newDekontImage = _appDocumentsDirectory + "/" + "${_currentUserReceiptNo}" + ".jpg";
        await new File(newDekontImage).writeAsBytesSync(new_jpeg);
    
      return true;
    }
    

    // TODO: 4 - MAIN WIDGET BUILD

    @override
      Widget build(BuildContext context) {
        capitalHeight = MediaQuery.of(context).size.height;
        capitalWidth = MediaQuery.of(context).size.width;
    
        if (imageOkay == true) {
          return new Scaffold(
            resizeToAvoidBottomPadding: true,
            appBar: new AppBar(
              title: new Text("Customer Receipt"),
              backgroundColor: const Color(0xFF7CB342),
              elevation: 0.0,
              actions: <Widget>[
                new Container(
                  padding: EdgeInsets.only(right: 10.0),
                  child: new Icon(Icons.mail),
                )
              ],
            ),
            body: new Column(
              children: <Widget>[
                new Padding(
                  padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                  child: new Center(
                    child: new Container(
                      width: capitalWidth,
                      height: capitalHeight / 2.3,
                      color: Colors.black54, //capitalLightGreen,
                      child: new Container(
                        width: capitalWidth - 20.0,
                        height: capitalHeight / 2.3,
                        child: Image.file(File('$newDekontImage')),
                      )
                    ),
                  )
                ),
              ],
            ),
          );
        } else {
          return new Scaffold(
              resizeToAvoidBottomPadding: true,
              appBar: new AppBar(
                title: new Text("Customer Receipt"),
                backgroundColor: const Color(0xFF7CB342),
                elevation: 0.0,
                actions: <Widget>[
                  new Container(
                    padding: EdgeInsets.only(right: 10.0),
                    child: new Icon(Icons.mail),
                  )
                ],
              ),
              body: new Center(
                child: new CircularProgressIndicator(),
              ));
        }
      }
    

相关问题