1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import com.baidu.aip.ocr.AipOcr; import lombok.extern.slf4j.Slf4j; import org.json.JSONObject;
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap;
@Slf4j public class OcrUtil {
public static final String APP_ID = "APP_ID"; public static final String API_KEY = "API_KEY"; public static final String SECRET_KEY = "SECRET_KEY";
private static AipOcr ocr;
static { ocr = new AipOcr(APP_ID, API_KEY, SECRET_KEY); }
public static String idcard(byte[] data, boolean flag) { HashMap<String, String> options = new HashMap<String, String>(); options.put("detect_direction", "true"); options.put("detect_risk", "true"); JSONObject res; if (flag) { res = ocr.idcard(data, "front", options); if (res.getString("image_status").equals("normal")) { return res.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words"); } else { log.error("身份证识别识别:" + res.getString("image_status")); } } else { res = ocr.idcard(data, "back", options); log.info(res.toString()); return "无法识别身份证号,这是国徽面"; } return null; }
public static String busine(byte[] data) { JSONObject res = ocr.businessLicense(data, new HashMap<>()); return res.getJSONObject("words_result").getJSONObject("证件编号").getString("words"); }
public static void main(String[] args) throws IOException { String imgName = "E:\\图片\\test\\sfz-B.jpg"; FileInputStream fis = new FileInputStream(new File(imgName)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] arr = new byte[1024]; int len; while ((len = fis.read(arr)) != -1) { baos.write(arr, 0, len); } System.out.println(imgName + " ---> " + idcard(baos.toByteArray(), false)); } }
|