当前位置: 代码网 > it编程>编程语言>C# > 基于C#编写一个接受图片流的OCR识别接口

基于C#编写一个接受图片流的OCR识别接口

2024年05月18日 C# 我要评论
示例代码using microsoft.aspnetcore.mvc;using system;using system.io;using system.threading.tasks;namespa

示例代码

using microsoft.aspnetcore.mvc;
using system;
using system.io;
using system.threading.tasks;

namespace myapi.controllers
{
    [apicontroller]
    [route("[controller]")]
    public class ocrcontroller : controllerbase
    {
        [httppost("ocr")]
        public async task<iactionresult> ocrtextasync()
        {
            try
            {
                // 检查是否有文件被上传
                if (request.form.files.count > 0)
                {
                    // 获取上传的文件
                    var file = request.form.files[0];

                    // 将文件转换为字节数组
                    using (var memorystream = new memorystream())
                    {
                        await file.copytoasync(memorystream);
                        byte[] imagedata = memorystream.toarray();

                        return ok("ocr result");
                    }
                }
                else
                {
                    return badrequest("no file uploaded");
                }
            }
            catch (exception ex)
            {
                return statuscode(500, $"internal server error: {ex}");
            }
        }
    }
}

调用示例代码:

    private async void button1_click(object sender, eventargs e)
    {
        try
        {
            openfiledialog filedialog = new openfiledialog();
            filedialog.multiselect = true;
            filedialog.title = "请选择图片";
            // filedialog.filter = "所有文件(*pdf*)|*.jpg*"; //设置要选择的文件的类型
            if (filedialog.showdialog() == dialogresult.ok)
            {
                string file = filedialog.filename;//返回文件的完整路径     
                                                  // textbox1.text = file;
                picturebox1.image = image.fromfile(file);

                memorystream stream = new memorystream();
                picturebox1.image.save(stream, system.drawing.imaging.imageformat.jpeg);
                byte[] imagedata = stream.getbuffer();
                await testapiasync(imagedata);
            }

        }
        catch (exception ex)
        {

            messagebox.show("请选择正确的图片");
        }
    }

    private async task testapiasync(byte[] imagedata)
    {
        string url = "http://localhost:5000/api/ocr/ocr";

        // 创建 httpclient 实例
        using (var httpclient = new httpclient())
        using (var formdata = new multipartformdatacontent())
        {
            try
            {
                formdata.add(new bytearraycontent(imagedata), "file", "image.jpg");

                // 发送 post 请求到接口
                httpresponsemessage response = await httpclient.postasync(url, formdata);

                // 检查响应是否成功
                if (response.issuccessstatuscode)
                {
                    // 读取响应内容
                    string result = await response.content.readasstringasync();
                    console.writeline("ocr 结果:" + result);
                }
                else
                {
                    console.writeline("请求失败,状态码:" + response.statuscode);
                }
            }
            catch (exception ex)
            {
                console.writeline("发生异常:" + ex.message);
            }
        }
    }

知识拓展

下面小编为大家整理了使用c#实现ocr本地图片识别文字的示例代码,希望对大家有所帮助

文字识别

 var apikey = "f--------------------x"; //自己申请的key
  var secretkey = "h----------------------"; //自己申请的key
  
  ocr client = new ocr(apikey, secretkey)
    {
            timeout = 30000//延时时间
   };
//本地图片识别文字
var image = file.readallbytes("图片文件路径");
	// 调用通用文字识别, 图片参数为本地图片,可能会抛出网络等异常,请使用try/catch捕获
	var result = client.generalbasic(image);
	console.writeline(result);
	// 如果有可选参数
	var options = new dictionary<string, object>{
	    {"language_type", "chn_eng"},
	    {"detect_direction", "true"},
	    {"detect_language", "true"},
	    {"probability", "true"}
	};
	// 带参数调用通用文字识别, 图片参数为本地图片
	result = client.generalbasic(image, options);

网络图片识别

//网络图片识别
 var url = "https//www.x.com/sample.jpg";
	// 调用通用文字识别, 图片参数为远程url图片,可能会抛出网络等异常,请使用try/catch捕获
	var result = client.generalbasicurl(url);
	console.writeline(result);
	// 如果有可选参数
	var options = new dictionary<string, object>{
	    {"language_type", "chn_eng"},
	    {"detect_direction", "true"},
	    {"detect_language", "true"},
	    {"probability", "true"}
	};
	// 带参数调用通用文字识别, 图片参数为远程url图片
	result = client.generalbasicurl(url, options);

到此这篇关于基于c#编写一个接受图片流的ocr识别接口的文章就介绍到这了,更多相关c# ocr识别接口内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com