Flutter文字识别与缩放插件flutter_scalable_ocr的使用
Flutter Scalable OCR 的使用
flutter_scalable_ocr
是一个基于 Google ML Kit 文本识别功能的 Flutter 插件,旨在解决从相机的部分区域而不是整个屏幕获取文本的问题。本文将详细介绍如何在 Flutter 项目中使用这个插件。
功能特性
- 从相机的狭窄窗口扫描文本,而不是整个屏幕。
- 提供两种方法:
getScannedText
: 返回读取的文本字符串。getRawData
: 返回包含TextElement
对象的列表。
- 支持缩放和手势操作。
使用步骤
1. 添加依赖
首先,在你的 pubspec.yaml
文件中添加 flutter_scalable_ocr
依赖:
dependencies:
flutter_scalable_ocr: ^1.0.1
然后运行 flutter pub get
来安装依赖。
2. 导入包
在需要使用该插件的 Dart 文件中导入它:
import 'package:flutter_scalable_ocr/flutter_scalable_ocr.dart';
3. 配置权限
由于该插件依赖于 camera
包,请确保在 Android 和 iOS 上配置了相应的权限。参考 Camera Package 的文档来设置权限。
4. 使用示例
以下是一个完整的示例代码,展示了如何集成 flutter_scalable_ocr
到你的 Flutter 应用中:
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_scalable_ocr/flutter_scalable_ocr.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Scalable OCR',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Scalable OCR'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String text = "";
final StreamController<String> controller = StreamController<String>();
bool torchOn = false;
int cameraSelection = 0;
bool lockCamera = true;
bool loading = false;
final GlobalKey<ScalableOCRState> cameraKey = GlobalKey<ScalableOCRState>();
void setText(value) {
controller.add(value);
}
[@override](/user/override)
void dispose() {
controller.close();
super.dispose();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
!loading
? ScalableOCR(
key: cameraKey,
torchOn: torchOn,
cameraSelection: cameraSelection,
lockCamera: lockCamera,
paintboxCustom: Paint()
..style = PaintingStyle.stroke
..strokeWidth = 4.0
..color = const Color.fromARGB(153, 102, 160, 241),
boxLeftOff: 5,
boxBottomOff: 2.5,
boxRightOff: 5,
boxTopOff: 2.5,
boxHeight: MediaQuery.of(context).size.height / 3,
getRawData: (value) {
inspect(value);
},
getScannedText: (value) {
setText(value);
})
: Padding(
padding: const EdgeInsets.all(17.0),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
height: MediaQuery.of(context).size.height / 3,
width: MediaQuery.of(context).size.width,
child: const Center(
child: CircularProgressIndicator(),
),
),
),
StreamBuilder<String>(
stream: controller.stream,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
return Result(text: snapshot.data ?? "");
},
),
Column(
children: [
ElevatedButton(
onPressed: () {
setState(() {
loading = true;
cameraSelection = cameraSelection == 0 ? 1 : 0;
});
Future.delayed(const Duration(milliseconds: 150), () {
setState(() {
loading = false;
});
});
},
child: const Text("Switch Camera")),
ElevatedButton(
onPressed: () async {
setState(() {
loading = true;
torchOn = !torchOn;
});
Future.delayed(const Duration(milliseconds: 150), () {
setState(() {
loading = false;
});
});
},
child: const Text("Toggle Torch")),
ElevatedButton(
onPressed: () {
setState(() {
loading = true;
lockCamera = !lockCamera;
});
Future.delayed(const Duration(milliseconds: 150), () {
setState(() {
loading = false;
});
});
},
child: const Text("Toggle Lock Camera")),
],
)
],
),
),
);
}
}
class Result extends StatelessWidget {
const Result({
Key? key,
required this.text,
}) : super(key: key);
final String text;
[@override](/user/override)
Widget build(BuildContext context) {
return Text("Readed text: $text");
}
}
更多关于Flutter文字识别与缩放插件flutter_scalable_ocr的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter文字识别与缩放插件flutter_scalable_ocr的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中集成和使用flutter_scalable_ocr
插件进行文字识别与缩放的示例代码。flutter_scalable_ocr
插件结合了文字识别(OCR)和图像缩放功能,非常适合处理不同大小的图像并从中提取文本。
1. 添加依赖
首先,在pubspec.yaml
文件中添加flutter_scalable_ocr
依赖:
dependencies:
flutter:
sdk: flutter
flutter_scalable_ocr: ^最新版本号 # 请替换为实际最新版本号
然后运行flutter pub get
来安装依赖。
2. 导入包
在需要使用OCR功能的Dart文件中导入flutter_scalable_ocr
包:
import 'package:flutter_scalable_ocr/flutter_scalable_ocr.dart';
3. 使用插件
下面是一个完整的示例,展示了如何从图像中识别文字并缩放图像:
import 'package:flutter/material.dart';
import 'package:flutter_scalable_ocr/flutter_scalable_ocr.dart';
import 'dart:ui' as ui;
import 'dart:typed_data';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: OcrScreen(),
);
}
}
class OcrScreen extends StatefulWidget {
@override
_OcrScreenState createState() => _OcrScreenState();
}
class _OcrScreenState extends State<OcrScreen> {
late FlutterScalableOcr _ocr;
Uint8List? _imageBytes;
String _recognizedText = '';
@override
void initState() {
super.initState();
_ocr = FlutterScalableOcr();
// 加载示例图像(这里假设你有一个图像资产)
rootBundle.load('assets/sample_image.jpg').then((data) {
setState(() {
_imageBytes = data.buffer.asUint8List();
});
_performOCR();
});
}
Future<void> _performOCR() async {
if (_imageBytes != null) {
try {
final result = await _ocr.recognizeTextFromImage(_imageBytes!);
setState(() {
_recognizedText = result.text;
});
} catch (e) {
print('OCR Error: $e');
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Scalable OCR Example'),
),
body: Column(
children: [
Expanded(
child: _imageBytes != null
? Image.memory(_imageBytes!)
: Center(child: CircularProgressIndicator()),
),
Text(
'Recognized Text:',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
Text(
_recognizedText,
style: TextStyle(fontSize: 16),
),
],
),
);
}
@override
void dispose() {
_ocr.dispose();
super.dispose();
}
}
4. 添加图像资产
确保在pubspec.yaml
文件中添加图像资产路径,例如:
flutter:
assets:
- assets/sample_image.jpg
然后将你的图像文件(例如sample_image.jpg
)放在assets
文件夹中。
5. 运行应用
现在,你可以运行你的Flutter应用,它将加载图像,执行OCR,并在屏幕上显示识别的文本。
这个示例展示了基本的OCR和图像显示功能。根据实际需求,你可能需要调整图像加载方式、错误处理、UI布局等。flutter_scalable_ocr
插件提供了丰富的功能,你可以查阅其官方文档以了解更多高级用法。