Flutter文本识别插件fl_mlkit_text_recognize的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter文本识别插件 fl_mlkit_text_recognize 的使用

基于 Google ML Kit 实现快速稳定识别文字功能,支持 Android 和 iOS。相机相关功能依赖于 fl_camera 插件。

使用说明

1. 添加相机权限

在 iOS 中,需要添加相机权限:

<key>NSCameraUsageDescription</key>
<string>是否允许FlMlKitTextRecognize使用你的相机?</string>

2. 示例代码

以下是一个完整的示例,展示了如何使用 fl_mlkit_text_recognize 插件进行文本识别。

主页面

import 'package:example/image_recognize.dart';
import 'package:example/mlkit_text_recognize.dart';
import 'package:fl_extended/fl_extended.dart';
import 'package:fl_mlkit_text_recognize/fl_mlkit_text_recognize.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MaterialApp(
      navigatorKey: FlExtended().navigatorKey,
      scaffoldMessengerKey: FlExtended().scaffoldMessengerKey,
      debugShowCheckedModeBanner: false,
      theme: ThemeData.light(useMaterial3: true),
      darkTheme: ThemeData.dark(useMaterial3: true),
      home: _App(),
      title: 'FlMlKitTextRecognize'));
}

class _App extends StatefulWidget {
  [@override](/user/override)
  _AppState createState() => _AppState();
}

class _AppState extends State<_App> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBarText('Fl MlKit Text Recognize'),
        body: Universal(width: double.infinity, children: [
          ElevatedText(
              onPressed: () => openCamera(), text: 'Turn on camera recognize'),
          ElevatedText(onPressed: scanImage, text: 'Image recognize'),
        ]));
  }

  void scanImage() {
    push(const ImageRecognizePage());
  }

  Future<void> openCamera() async {
    final hasPermission = await getPermission(Permission.camera);
    if (hasPermission) push(const FlMlKitTextRecognizePage());
  }
}

文本识别页面

import 'package:fl_mlkit_text_recognize/fl_mlkit_text_recognize.dart';
import 'package:flutter/material.dart';

class FlMlKitTextRecognizePage extends StatelessWidget {
  const FlMlKitTextRecognizePage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Text Recognition'),
      ),
      body: FlMlKitTextRecognize(
        frequency: 500, // 建议设置为500-1000毫秒
        camera: camera, // 需要预览的相机
        resolution: CameraResolution.high, // 预览相机支持的分辨率
        autoRecognize: false, // 是否自动识别,默认为true
        overlay: const ScannerLine(), // 显示在预览上层
        fit: BoxFit.fitWidth, // 相机预览位置
        onFlashChanged: (FlashState state) {
          // 闪光灯状态回调
        },
        onDataChanged: (AnalysisTextModel data) {
          // 文本识别回调
          if (data.text != null && data.text!.isNotEmpty) {
            // 处理识别到的文本
          }
        },
        uninitialized: Container(
          color: Colors.black,
          alignment: Alignment.center,
          child: const Text(
            'Camera not initialized',
            style: TextStyle(color: Colors.white),
          ),
        ),
        recognizedLanguage: RecognizedLanguage.latin, // 识别文本的语言类型
      ),
    );
  }
}

3. 方法调用

以下是该插件提供的一些方法:

void func() {
  /// 设置识别文本的语言类型
  controller.setRecognizedLanguage();

  /// 识别图片字节
  controller.scanImageByte();

  /// 打开/关闭闪光灯
  controller.setFlashMode();

  /// 相机缩放
  controller.setZoomRatio();

  /// 暂停识别
  controller.pauseRecognize();

  /// 开始识别
  controller.startRecognize();
}

4. UI 组件

为了更好地展示识别结果,可以使用以下组件:

class CodeBox extends StatelessWidget {
  const CodeBox(this.model, {super.key, this.expanded = true});

  final AnalysisTextModel? model;
  final bool expanded;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Universal(
      expanded: expanded,
      isScroll: expanded,
      children: <Widget>[
        TextBox('height=', model?.height),
        TextBox('width=', model?.width),
        TextBox('value=', model?.text),
        const Divider(),
        ...model?.textBlocks
                ?.map((TextBlock b) => SizedBox(
                    width: double.infinity, child: TextBox('TextBlock', b.text)))
                .toList() ??
            []
      ],
    );
  }
}

class TextBox extends StatelessWidget {
  final dynamic keyName;
  final dynamic value;

  const TextBox(this.keyName, this.value, {super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Visibility(
        visible: value != null &&
            value.toString().isNotEmpty &&
            value.toString() != 'null',
        child: Universal(
            padding: const EdgeInsets.all(10),
            direction: Axis.horizontal,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('$keyName: ',
                  style: const TextStyle(fontWeight: FontWeight.bold)),
              Text(value.toString()).expanded,
            ]));
  }
}

更多关于Flutter文本识别插件fl_mlkit_text_recognize的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文本识别插件fl_mlkit_text_recognize的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用fl_mlkit_text_recognize插件进行文本识别的代码示例。这个插件依赖于Google的ML Kit,用于在Flutter应用中实现文本识别功能。

首先,你需要在你的pubspec.yaml文件中添加fl_mlkit_text_recognize依赖:

dependencies:
  flutter:
    sdk: flutter
  fl_mlkit_text_recognize: ^最新版本号  # 请替换为实际的最新版本号

然后运行flutter pub get来获取依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用文本识别功能:

  1. 导入必要的包
import 'package:flutter/material.dart';
import 'package:fl_mlkit_text_recognize/fl_mlkit_text_recognize.dart';
import 'dart:typed_data';
import 'dart:ui' as ui;
  1. 定义一个方法来处理图像并识别文本
Future<String?> recognizeTextFromImage(Uint8List imageBytes) async {
  final TextRecognizer textRecognizer = TextRecognizer();
  try {
    final RecognitionResult result = await textRecognizer.processImage(imageBytes);
    return result.text;
  } catch (e) {
    print("Error recognizing text: $e");
    return null;
  } finally {
    textRecognizer.close();
  }
}
  1. 从相机或图库中选择图像并识别文本

这里我们使用image_picker插件来选择图像,你需要在pubspec.yaml中添加image_picker依赖:

dependencies:
  image_picker: ^最新版本号  # 请替换为实际的最新版本号

然后,在你的代码中:

import 'package:image_picker/image_picker.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Text Recognition'),
        ),
        body: TextRecognitionScreen(),
      ),
    );
  }
}

class TextRecognitionScreen extends StatefulWidget {
  @override
  _TextRecognitionScreenState createState() => _TextRecognitionScreenState();
}

class _TextRecognitionScreenState extends State<TextRecognitionScreen> {
  final ImagePicker _picker = ImagePicker();
  String? _recognizedText;

  Future<void> _pickImage(ImageSource source) async {
    final XFile? image = await _picker.pickImage(source: source);
    if (image != null) {
      final Uint8List imageBytes = await image.readAsBytes();
      _recognizedText = await recognizeTextFromImage(imageBytes);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ElevatedButton(
            onPressed: () => _pickImage(ImageSource.camera),
            child: Text('Pick from Camera'),
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () => _pickImage(ImageSource.gallery),
            child: Text('Pick from Gallery'),
          ),
          SizedBox(height: 20),
          if (_recognizedText != null)
            Text(
              'Recognized Text:\n$_recognizedText',
              style: TextStyle(fontSize: 18),
            ),
        ],
      ),
    );
  }
}

这个示例代码展示了如何从相机或图库中选择图像,并使用fl_mlkit_text_recognize插件来识别图像中的文本。识别结果会显示在屏幕上。

注意:

  • 确保在Android和iOS项目中正确配置权限,特别是相机和存储权限。
  • 由于ML Kit和Flutter插件的更新,代码和依赖版本可能会有所变化,请参考官方文档和插件仓库的最新信息。
回到顶部