全部产品
Search
文档中心

内容安全:图片OCR识别

更新时间:Jul 31, 2023

本文介绍了如何使用.NET SDK图片OCR接口,识别图片中的文字信息。

前提条件

已安装.NET依赖。关于安装.NET依赖的具体操作,请参见安装.NET依赖

说明

请一定按照安装.NET依赖页面中的版本安装,否则会导致调用失败。

提交图片同步检测任务

接口

描述

支持的Region

ImageSyncScanRequest

提交图片OCR同步识别任务,对图片中的文字进行识别(scene=ocr)。

  • cn-shanghai

  • cn-beijing

  • cn-shenzhen

  • ap-southeast-1

示例代码

using System;
using Newtonsoft.Json;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Green.Model.V20180509;
using System.Collections.Generic;

namespace csharp_sdk_sample
{
    class Program
    {
        static void Main(string[] args)
        {
            /**
             * 常见获取环境变量方式:
             *     获取RAM用户AccessKey ID:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     获取RAM用户AccessKey Secret:Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.GetProfile(
                    "cn-shanghai",
                    "建议从环境变量中获取RAM用户AccessKey ID",
                    "建议从环境变量中获取RAM用户AccessKey Secret");
            DefaultAcsClient client = new DefaultAcsClient(profile);

            ImageSyncScanRequest request = new ImageSyncScanRequest();
            request.AcceptFormat = FormatType.JSON;
            request.ContentType = FormatType.JSON;
            request.Method = MethodType.POST;
            request.Encoding = "UTF-8";

            Dictionary<string, object> task1 = new Dictionary<string, object>();
            task1.Add("dataId", "检测数据ID");
            //task1.Add("url", "待检测图片链接地址");
            task1.Add("url", "http://example.com/xx.jpg");

            // 示例:身份证正面识别。
            Dictionary<string, object> cardExtras = new Dictionary<string, object>();
            cardExtras.Add("card", "id-card-front");

            Dictionary<string, object> httpBody = new Dictionary<string, object>();
            // scenes:检测场景。
            httpBody.Add("scenes", new List<string> { "ocr" });
            httpBody.Add("bizType", "业务场景");
            httpBody.Add("extras", cardExtras);
            httpBody.Add("tasks", new List<Dictionary<string, object>> { task1 });

            request.SetContent(System.Text.Encoding.Default.GetBytes(JsonConvert.SerializeObject(httpBody)), "utf-8", FormatType.JSON);
            try
            {
                ImageSyncScanResponse response = client.GetAcsResponse(request);
                if (response.HttpResponse.Status != 200)
                {
                    Console.WriteLine("the request failed. status:{0}", response.HttpResponse.Status);
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
    }
}