79 lines
2.4 KiB
C#
79 lines
2.4 KiB
C#
#nullable enable
|
|
using Furion.DependencyInjection;
|
|
using Microsoft.Extensions.Options;
|
|
using YD_Event.Core.Options;
|
|
using AlibabaCloud.OpenApiClient.Models;
|
|
using AlibabaCloud.SDK.Ocr20191230;
|
|
using AlibabaCloud.SDK.Ocr20191230.Models;
|
|
using System.Threading.Tasks;
|
|
using System;
|
|
|
|
namespace YD_Event.Core.Ocr;
|
|
|
|
/// <summary>
|
|
/// OCR服务实现
|
|
/// </summary>
|
|
public class OcrService : ITransient
|
|
{
|
|
private readonly AliyunOcrOptions _options;
|
|
|
|
public OcrService(IOptions<AliyunOcrOptions> options)
|
|
{
|
|
_options = options.Value;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 识别身份证
|
|
/// </summary>
|
|
/// <param name="imageUrl">图片URL</param>
|
|
/// <returns></returns>
|
|
public async Task<OcrResult> RecognizeIdCardAsync(string imageUrl)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(imageUrl))
|
|
{
|
|
return new OcrResult { Success = false, Message = "图片URL不能为空" };
|
|
}
|
|
|
|
try
|
|
{
|
|
var config = new AlibabaCloud.OpenApiClient.Models.Config
|
|
{
|
|
AccessKeyId = _options.AccessKeyId,
|
|
AccessKeySecret = _options.AccessKeySecret,
|
|
Endpoint = _options.Endpoint
|
|
};
|
|
|
|
var client = new Client(config);
|
|
var request = new RecognizeIdentityCardRequest
|
|
{
|
|
ImageURL = imageUrl,
|
|
Side = "face" // 默认正面
|
|
};
|
|
|
|
// 使用 RuntimeOptions 可以自定义超时等配置,这里简单起见使用默认
|
|
var response = await client.RecognizeIdentityCardAsync(request);
|
|
|
|
if (response.Body != null && response.Body.Data != null && response.Body.Data.FrontResult != null)
|
|
{
|
|
var data = response.Body.Data.FrontResult;
|
|
// 解析结果
|
|
return new OcrResult
|
|
{
|
|
Success = true,
|
|
Name = data.Name,
|
|
Gender = data.Gender,
|
|
IdCardNumber = data.IDNumber,
|
|
BirthDate = data.BirthDate,
|
|
Message = "识别成功"
|
|
};
|
|
}
|
|
|
|
return new OcrResult { Success = false, Message = "未识别到有效身份证信息" };
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new OcrResult { Success = false, Message = $"OCR识别异常: {ex.Message}" };
|
|
}
|
|
}
|
|
}
|