react native 集成百度智能云文字识别(Android)

首先先申请账号,然后创建应用,创建应用一定要填写包名

创建成功后,查看应用会有一个安全模式设置,将这个License文件下载到本地

下载SDK,然后解压

将ocr-sdk.jar文件拷到 app/libs

将ocr-sdk.jar同级其余文件拷到main/jniLibs文件夹中

Android Studio 配置

app/build.gradle 引入 ocr-sdk.jar 文件

将之前下载好的aip.license文件拷到assets文件夹下(此文件防止被反编译后盗取AK/SK,详情

 

添加权限配置

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

proguard-rules 添加混淆规则

-keep class com.baidu.ocr.sdk.**{*;}
-dontwarn com.baidu.ocr.**

创建原生模块

 


所有方法参考事例demo里的 java 文件以及官方文档

1. IDCardActivity.java 文件实现身份证识别

2. RecognizeService.java 文件实现其余的识别方法


 

OcrModule

package com.'你的包名'.ocr;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.BankCardParams;
import com.baidu.ocr.sdk.model.BankCardResult;
import com.baidu.ocr.sdk.model.GeneralBasicParams;
import com.baidu.ocr.sdk.model.GeneralResult;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.sdk.model.OcrRequestParams;
import com.baidu.ocr.sdk.model.OcrResponseResult;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.io.File;

public class OcrModule extends ReactContextBaseJavaModule {

    private ReactApplicationContext context;

    public OcrModule(ReactApplicationContext reactContext) {
        super(reactContext);
        context = reactContext;
    }

    @Override
    public String getName() {
        return "OcrModule";
    }

    /**
     * 初始化token
     */
    @ReactMethod
    private void init() {
        OCR.getInstance(context).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                WritableMap params = Arguments.createMap();
                params.putString("token", token);
                sendEvent("init", params);
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                WritableMap params = Arguments.createMap();
                params.putDouble("error", error.getErrorCode());
                sendEvent("init", params);
            }
        }, context);
    }

    /**
     * 通用文字识别
     * @param filePath 文件路径
     */
    @ReactMethod
    public void recGeneralBasic(String filePath) {
        GeneralBasicParams param = new GeneralBasicParams();
        param.setDetectDirection(true);
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeGeneralBasic(param, new OnResultListener<GeneralResult>() {
            @Override
            public void onResult(GeneralResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recGeneralBasic", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recGeneralBasic", params);
            }
        });
    }

    /**
     * 银行卡识别
     * @param filePath 文件路径
     */
    @ReactMethod
    public void recBankCard(String filePath) {
        BankCardParams param = new BankCardParams();
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeBankCard(param, new OnResultListener<BankCardResult>() {
            @Override
            public void onResult(BankCardResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recBankCard", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recBankCard", params);
            }
        });
    }

    /**
     * 身份证识别
     * @param filePath 文件路径
     * @param idCardSide 身份证正反面
     */
    @ReactMethod
    public void recIDCard(String filePath, String idCardSide) {
        IDCardParams param = new IDCardParams();
        param.setIdCardSide(idCardSide);
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recIDCard", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recIDCard", params);
            }
        });
    }

    /**
     * 行驶证识别
     * @param filePath 文件路径
     */
    @ReactMethod
    public void recVehicleLicense(String filePath) {
        OcrRequestParams param = new OcrRequestParams();
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeVehicleLicense(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recVehicleLicense", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recVehicleLicense", params);
            }
        });
    }

    /**
     * 驾驶证识别
     * @param filePath 文件路径
     */
    @ReactMethod
    public void recDrivingLicense(String filePath) {
        OcrRequestParams param = new OcrRequestParams();
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeDrivingLicense(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recDrivingLicense", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recDrivingLicense", params);
            }
        });
    }

    /**
     * 车牌识别
     * @param filePath 文件路径
     */
    @ReactMethod
    public void recLicensePlate(String filePath) {
        OcrRequestParams param = new OcrRequestParams();
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeLicensePlate(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recLicensePlate", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recLicensePlate", params);
            }
        });
    }

    /**
     * 营业执照识别
     * @param filePath 文件路径
     */
    @ReactMethod
    public void recBusinessLicense(String filePath) {
        OcrRequestParams param = new OcrRequestParams();
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeBusinessLicense(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recBusinessLicense", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recBusinessLicense", params);
            }
        });
    }

    /**
     * 通用票据识别
     * @param filePath 文件路径
     */
    @ReactMethod
    public void recReceipt(String filePath) {
        OcrRequestParams param = new OcrRequestParams();
        param.setImageFile(new File(filePath));

        OCR.getInstance(context).recognizeReceipt(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                WritableMap params = Arguments.createMap();
                params.putString("result", result.getJsonRes());
                sendEvent("recReceipt", params);
            }

            @Override
            public void onError(OCRError error) {
                WritableMap params = Arguments.createMap();
                params.putString("msg", error.getMessage());
                params.putDouble("errCode", error.getErrorCode());
                sendEvent("recReceipt", params);
            }
        });
    }

    private void sendEvent(String eventName, WritableMap params) {
        context.
                getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }
}

OcrPackage

package com.'你的包名'.ocr;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class OcrPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new OcrModule(reactContext));
        return modules;
    }
}

MainApplication中调用此方法

App.js ( 没有做Promise处理 )

import React, {Component} from 'react';
import {
  View,
  Text,
  StatusBar,
  NativeModules,
  DeviceEventEmitter,
  StyleSheet,
} from 'react-native';
import ImagePicker from 'react-native-image-picker'

const ocr = NativeModules.OcrModule;
const options = {
  title: 'Select Avatar',
  storageOptions: {
    skipBackup: true,
    path: 'images',
  },
};

export default class App extends Component {
  componentDidMount = () => {
    DeviceEventEmitter.once('init', result => {
      console.log(result)
    })
    // 通用文字识别
    DeviceEventEmitter.addListener('recGeneralBasic', result => {
      console.log(JSON.parse(result.result))
    })
    // 银行卡识别
    DeviceEventEmitter.addListener('recBankCard', result => {
      console.log(JSON.parse(result.result))
    })
    // 身份证识别
    DeviceEventEmitter.addListener('recIDCard', result => {
      console.log(JSON.parse(result.result))
    })
    // 行驶证识别
    DeviceEventEmitter.addListener('recVehicleLicense', result => {
      console.log(JSON.parse(result.result))
    })
    // 驾驶证识别
    DeviceEventEmitter.addListener('recDrivingLicense', result => {
      console.log(JSON.parse(result.result))
    })
    // 车牌识别
    DeviceEventEmitter.addListener('recLicensePlate', result => {
      console.log(JSON.parse(result.result))
    })
    // 营业执照识别
    DeviceEventEmitter.addListener('recBusinessLicense', result => {
      console.log(JSON.parse(result.result))
    })
    // 通用票据识别
    DeviceEventEmitter.addListener('recReceipt', result => {
      console.log(JSON.parse(result.result))
    })
    ocr.init()
  };

  render() {
    return (
      <View>
        <StatusBar barStyle="default" />
        <View>
          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recGeneralBasic(path)
            });
          }}>
            通用文字识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recBankCard(path)
            });
          }}>
            银行卡识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recIDCard(path, 'front')
            });
          }}>
            身份证正面识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recIDCard(path, 'back')
            });
          }}>
            身份证反面识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recVehicleLicense(path)
            });
          }}>
            行驶证识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recDrivingLicense(path)
            });
          }}>
            驾驶证识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recLicensePlate(path)
            });
          }}>
            车牌识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recBusinessLicense(path)
            });
          }}>
            营业执照识别
          </Text>

          <Text style={styles.text} onPress={() => {
            ImagePicker.showImagePicker(options, (response) => {
              const path = response.path;
              ocr.recReceipt(path)
            });
          }}>
            通用票据识别
          </Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  text: {
    marginLeft: 15,
    padding: 5,
    fontSize: 20,
  }
})

部分返回结果

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
React Native提供了一个称为Native Modules的机制,允许您在React Native应用程序中使用原生代码。因此,您可以使用Java或Kotlin编写原生Android代码,并将其与React Native应用程序集成。以下是一些步骤: 1.创建一个新的Android库项目。 2.在您的React Native项目中创建一个新的Native Module。 3.将您的原生代码添加到Android库项目中。 4.编写Java或Kotlin代码来公开原生方法。 5.在React Native Native Module中使用这些方法。 6.构建并运行您的React Native应用程序。 这里是一个简单的例子,说明如何在React Native应用程序中使用原生Android模块: 1.创建一个新的Android库项目 在Android Studio中,选择“File” > “New” > “New Module”。然后选择“Android Library”并按照向导中的说明创建一个新的Android库项目。 2.在您的React Native项目中创建一个新的Native Module 在React Native项目的根目录下,运行以下命令: ``` react-native create-library MyNativeModule ``` 此命令将创建一个名为MyNativeModule的新目录。在此目录中,您可以添加一个名为MyNativeModule.java的文件。 3.将您的原生代码添加到Android库项目中 将您的原生代码复制到Android库项目中的src/main/java目录中。 4.编写Java或Kotlin代码来公开原生方法 在您的Java或Kotlin类中,使用@ReactMethod注释来标记要公开给React Native的原生方法。例如: ``` @ReactMethod public void showToast(String message) { Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show(); } ``` 5.在React Native Native Module中使用这些方法 在您的React Native应用程序中,导入MyNativeModule并调用其方法。例如: ``` import { NativeModules } from 'react-native'; const { MyNativeModule } = NativeModules; MyNativeModule.showToast('Hello, world!'); ``` 6.构建并运行您的React Native应用程序 在React Native应用程序的根目录中,运行以下命令以构建并运行您的应用程序: ``` react-native run-android ``` 这样,您就可以在React Native应用程序中使用原生Android模块了!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值