使用腾讯云OCR文字识别服务
腾讯云OCR服务提供了强大的文字识别能力,支持多种语言和场景的文字识别。以下是改写后的代码,使用腾讯云OCR SDK进行文字识别:
前提条件
- 腾讯云账号:您需要一个腾讯云账号,并在腾讯云控制台中创建一个OCR服务实例。
- API密钥:获取腾讯云OCR服务的
SecretId
和SecretKey
。https://console.cloud.tencent.com/cam/capi页面上新建密钥并记录。 - 安装腾讯云SDK:通过NuGet安装腾讯云OCR SDK。搜索TencentCloudSDK.Ocr安装即可。
- 代码如下:
private async Task<string> PerformOcr(string imagePath)
{
try
{
// 初始化腾讯云客户端
Credential cred = new Credential
{
SecretId = "",//自行填写
SecretKey = ""
};
HttpProfile httpProfile = new HttpProfile();
httpProfile.Endpoint = "ocr.tencentcloudapi.com";
ClientProfile clientProfile = new ClientProfile();
clientProfile.HttpProfile = httpProfile;
OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);//可以改为你的云服务其他地区,比如ap-guangzhou
// 读取图片文件
byte[] imageBytes = File.ReadAllBytes(imagePath);
string imageBase64 = Convert.ToBase64String(imageBytes);
// 构造请求参数
GeneralBasicOCRRequest req = new GeneralBasicOCRRequest
{
ImageBase64 = imageBase64
};
// 发起请求
GeneralBasicOCRResponse resp = await client.GeneralBasicOCR(req);
// 提取识别结果
string ocrText = string.Join("\n", resp.TextDetections.Select(d => d.DetectedText));
return ocrText;
}
catch (Exception ex)
{
MessageBox.Show($"OCR识别失败: {ex.Message}");
return string.Empty;
}
}
5、使用量可以https://console.cloud.tencent.com/ocr/overview查询,有免费的赠送使用次数,不要浪费。
评论0