Flutter光学字符识别插件ocr_scan的使用

Flutter光学字符识别插件ocr_scan的使用

OCR Scan

Pub Version

OCR扫描库适用于Flutter。它可以扫描文本、条形码、二维码等。

ScanPreview ScanFile
Demo Demo

要求

由于该包使用了 ML Kit,在项目中运行之前,请查看 要求

如何使用

  1. ocr_scan 添加到你的 pubspec.yaml 文件中。
  2. 导入所需的包或类。
import 'package:ocr_scan/ocr_scan.dart';

Widget buildPreview(BuildContext context) {
  final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context);

  return ScanPreview(
    scanProcess: process,
    scanDuration: const Duration(milliseconds: 2000 * 3),
    textRecognizerConfig: TextRecognizerConfig(
      zonePainter: ZonePainter(
        elements: [
          const Zone(
            Rect.fromLTWH(40, 100, 1200, 100),
            text: TextSpan(
              text: 'Zone: TextRecognizer',
              style: TextStyle(backgroundColor: Colors.red),
            ),
            paintingColor: Colors.red,
          ),
        ],
      ),
      onTextLine: ((int, List<TextLine>) value) {
        messenger.showSnackBar(SnackBar(
          duration: const Duration(milliseconds: 2000),
          content: Text(
            value.$2.fold(
              'TextRecognizer - Length ${value.$2.length}:',
              (String pre, TextLine e) => '$pre\n${e.text}',
            ),
          ),
        ));
      },
    ),
    barcodeScannerConfig: BarcodeScannerConfig(
      zonePainter: ZonePainter(
        rotation: InputImageRotation.rotation90deg,
        elements: [
          Zone(
            Rect.fromCenter(
              center: const Size(720, 1280).center(Offset.zero),
              width: 400,
              height: 400,
            ),
            text: const TextSpan(
              text: 'Zone: BarcodeScanner',
              style: TextStyle(backgroundColor: Colors.green),
            ),
            paintingColor: Colors.green,
          ),
        ],
      ),
      onBarcode: ((int, List<Barcode>) value) {
        messenger.showSnackBar(SnackBar(
          duration: const Duration(milliseconds: 2000),
          content: Text(
            value.$2.fold(
              'BarcodeScanner - Length ${value.$2.length}:',
              (String pre, Barcode e) => '$pre\n${e.displayValue}',
            ),
          ),
        ));
      },
    ),
  );
}

示例代码

以下是使用 ocr_scan 插件的完整示例代码:

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ocr_scan/ocr_scan.dart';

void main() {
  runApp(const MaterialApp(home: MainApp()));
}

class MainApp extends StatefulWidget {
  const MainApp({super.key});

  [@override](/user/override)
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  final ImagePicker picker = ImagePicker();
  XFile? image;
  bool process = false;

  bool get hasImage => image != null;
  ScaffoldMessengerState get messenger => ScaffoldMessenger.of(context);

  late final TextRecognizerConfig textRecognizerConfig = TextRecognizerConfig(
    zonePainter: ZonePainter(
      elements: [
        const Zone(
          Rect.fromLTWH(0, 24, 720, 400),
          text: TextSpan(
            text: 'Zone: TextRecognizer',
            style: TextStyle(backgroundColor: Colors.red),
          ),
          paintingColor: Colors.red,
        ),
      ],
    ),
    onTextLine: ((int, List<TextLine>) value) {
      messenger.showSnackBar(SnackBar(
        duration: const Duration(milliseconds: 2000),
        content: Text(
          value.$2.fold(
            'TextRecognizer - Length ${value.$2.length}:',
            (String pre, TextLine e) => '$pre\n${e.text}',
          ),
        ),
      ));
    },
  );
  late final BarcodeScannerConfig barcodeScannerConfig = BarcodeScannerConfig(
    zonePainter: ZonePainter(
      rotation: InputImageRotation.rotation90deg,
      elements: [
        Zone(
          Rect.fromCenter(
            center: const Size(720, 1280).center(Offset.zero),
            width: 400,
            height: 400,
          ),
          text: const TextSpan(
            text: 'Zone: BarcodeScanner',
            style: TextStyle(backgroundColor: Colors.green),
          ),
          paintingColor: Colors.green,
        ),
      ],
    ),
    onBarcode: ((int, List<Barcode>) value) {
      messenger.showSnackBar(SnackBar(
        duration: const Duration(milliseconds: 2000),
        content: Text(
          value.$2.fold(
            'BarcodeScanner - Length ${value.$2.length}:',
            (String pre, Barcode e) => '$pre\n${e.displayValue}',
          ),
        ),
      ));
    },
  );

  [@override](/user/override)
  void dispose() {
    super.dispose();
    textRecognizerConfig.zonePainter?.dispose();
    barcodeScannerConfig.zonePainter?.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Ocr Scan Example')),
      body: Center(
        child: Builder(builder: hasImage ? buildImage : buildPreview),
      ),
      bottomNavigationBar: buildBottomAppBar(),
    );
  }

  Widget buildBottomAppBar() {
    return BottomAppBar(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          ElevatedButton.icon(
            onPressed: hasImage
                ? null
                : () {
                    process = !process;
                    setState(() {});
                  },
            icon: const Icon(Icons.document_scanner),
            label: Text(process ? 'Stop' : 'Start'),
          ),
          IconButton(
            onPressed: hasImage
                ? null
                : () async {
                    image = await picker.pickImage(source: ImageSource.gallery);
                    setState(() {});
                  },
            icon: const Icon(Icons.image),
          ),
          IconButton(
            onPressed: hasImage
                ? null
                : () async {
                    image = await picker.pickImage(source: ImageSource.camera);
                    setState(() {});
                  },
            icon: const Icon(Icons.camera_alt),
          ),
          IconButton(
            onPressed: !hasImage
                ? null
                : () {
                    image = null;
                    setState(() {});
                  },
            icon: const Icon(Icons.close),
          ),
        ],
      ),
    );
  }

  Widget buildPreview(BuildContext context) {
    return ScanPreview(
      scanProcess: process,
      scanDuration: const Duration(milliseconds: 2000 * 3),
      textRecognizerConfig: textRecognizerConfig,
      barcodeScannerConfig: barcodeScannerConfig,
    );
  }

  Widget buildImage(BuildContext context) {
    return ScanFile(
      scanFile: File(image!.path),
      previewSize: const Size(720, 1280),
      textRecognizerConfig: textRecognizerConfig,
      barcodeScannerConfig: barcodeScannerConfig,
    );
  }
}

更多关于Flutter光学字符识别插件ocr_scan的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


在Flutter中,ocr_scan 是一个用于光学字符识别(OCR)的插件,允许你从图像中提取文本。以下是如何使用 ocr_scan 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 ocr_scan 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  ocr_scan: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入包

在你的 Dart 文件中导入 ocr_scan 包:

import 'package:ocr_scan/ocr_scan.dart';

3. 使用插件进行OCR

你可以使用 OcrScan 类来执行OCR操作。以下是一个简单的示例,展示如何从图像中提取文本:

import 'package:flutter/material.dart';
import 'package:ocr_scan/ocr_scan.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

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

class _OcrExampleState extends State<OcrExample> {
  String _extractedText = '';

  Future<void> _pickImageAndExtractText() async {
    final picker = ImagePicker();
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      final imageFile = File(pickedFile.path);
      final text = await OcrScan.scanText(imageFile.path);

      setState(() {
        _extractedText = text;
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('OCR Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _extractedText.isNotEmpty
                ? Text('Extracted Text: $_extractedText')
                : Text('No text extracted yet.'),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickImageAndExtractText,
              child: Text('Pick Image and Extract Text'),
            ),
          ],
        ),
      ),
    );
  }
}

void main() => runApp(MaterialApp(
  home: OcrExample(),
));
回到顶部