Flutter应用集成Google Cloud Vision OCR的资源选择及技术疑问
Flutter集成Google Cloud Vision OCR的资源选择疑问解答
1. 上述三个资源中哪些可用于我的Flutter应用?
三个资源都适配你的Flutter应用:
- 第一个是pub.dev提供的Google Cloud Vision API的Dart客户端库,封装了API调用逻辑,可直接在Flutter项目中引入使用
- 第二个是Google Cloud Vision的REST API端点,你可以通过Flutter的HTTP请求库直接向该端点发送请求,实现OCR功能
- 第三个是Flutter专用的Google ML Vision插件,封装了Google ML Kit的OCR能力(支持本地/云端两种模式),同样适配Flutter项目
2. 第一个和第三个资源是否为同一事物?
不是同一事物,核心差异如下:
- 第一个对接Google Cloud Vision API:属于纯云端OCR服务,必须联网使用,需绑定Google Cloud账号并配置API密钥,按调用量计费,适合复杂文本识别场景
- 第三个对接Google ML Kit Vision:支持本地设备端运行OCR(无需联网),也可选调用云端服务;本地模式免费,适合轻量文本识别,云端模式归属ML Kit服务体系,和Cloud Vision逻辑类似但服务入口不同
3. 是否有使用前两种方案的示例?
方案一:使用googleapis的vision.v1库
- 在
pubspec.yaml中添加依赖:
dependencies: googleapis: ^12.0.0 googleapis_auth: ^1.4.1
- 核心调用代码示例:
import 'dart:convert'; import 'dart:typed_data'; import 'package:googleapis/vision/v1.dart'; import 'package:googleapis_auth/auth_io.dart'; Future<String?> extractTextFromImage(Uint8List imageBytes) async { const apiKey = '你的Google Cloud API密钥'; final client = clientViaApiKey(apiKey); final visionApi = VisionApi(client); final request = AnnotateImageRequest() ..features = [Feature()..type = 'TEXT_DETECTION'] ..image = Image()..content = base64Encode(imageBytes); final response = await visionApi.images.annotate( BatchAnnotateImagesRequest()..requests = [request] ); client.close(); if (response.responses?.isNotEmpty == true) { final textAnnotations = response.responses![0].textAnnotations; return textAnnotations?.first.description; } return null; }
方案二:直接调用REST API端点
- 在
pubspec.yaml中添加HTTP依赖:
dependencies: http: ^1.1.0
- 核心请求代码示例:
import 'dart:convert'; import 'dart:typed_data'; import 'package:http/http.dart' as http; Future<String?> extractTextViaRest(Uint8List imageBytes) async { const apiKey = '你的Google Cloud API密钥'; final endpoint = Uri.parse('https://vision.googleapis.com/v1/images:annotate?key=$apiKey'); final requestBody = jsonEncode({ 'requests': [ { 'image': {'content': base64Encode(imageBytes)}, 'features': [{'type': 'TEXT_DETECTION'}] } ] }); final response = await http.post( endpoint, body: requestBody, headers: {'Content-Type': 'application/json'}, ); if (response.statusCode == 200) { final data = jsonDecode(response.body); final textAnnotations = data['responses'][0]['textAnnotations']; return textAnnotations?[0]['description']; } return null; }
内容的提问来源于stack exchange,提问作者cdt
相关产品推荐
相关产品推荐

