首页 > 解决方案 > 希望将控制台应用程序转换为 asap.net 网络表单

问题描述

我目前有这个控制台应用程序,它使用 Microsoft 的光学字符识别 (OCR) 从图像中提取单词。结果当前发布到控制台应用程序中,我想创建相同的东西,但用于网页表单。最好的方法是什么?我可以使用列表框或标签而不是 console.writeline 来显示结果吗?

这是控制台应用程序的代码

static class Program{ 

    // Add your Computer Vision subscription key and endpoint to your environment variables.
    const string subscriptionKey = ("********");    const string endpoint = ("https://wesam.cognitiveservices.azure.com/");

    // the OCR method endpoint
    static string uriBase = endpoint + "vision/v2.1/ocr";

    static async Task Main()
    {
        // Get the path and filename to process from the user.
        Console.WriteLine("Optical Character Recognition:");
        Console.Write("Enter the path to an image with text you wish to read: ");
        string imageFilePath = @"C:\Users\alabe\Downloads\Syria.jpg";


        if (File.Exists(imageFilePath))
        {
            // Call the REST API method.
            Console.WriteLine("\nWait a moment for the results to appear.\n");
            await MakeOCRRequest(imageFilePath);
        }
        else
        {
            Console.WriteLine("\nInvalid file path");
        }
        Console.WriteLine("\nPress Enter to exit...");
        Console.ReadLine();
    }

    /// <summary>
    /// Gets the text visible in the specified image file by using
    /// the Computer Vision REST API.
    /// </summary>
    /// <param name="imageFilePath">The image file with printed text.</param>
    static async Task MakeOCRRequest(string imageFilePath)
    {
        try
        {
            HttpClient client = new HttpClient();

            // Request headers.
            client.DefaultRequestHeaders.Add(
                "Ocp-Apim-Subscription-Key", subscriptionKey);

            // Request parameters. 
            // The language parameter doesn't specify a language, so the 
            // method detects it automatically.
            // The detectOrientation parameter is set to true, so the method detects and
            // and corrects text orientation before detecting text.
            string requestParameters = "language=unk&detectOrientation=true";

            // Assemble the URI for the REST API method.
            string uri = uriBase + "?" + requestParameters;

            HttpResponseMessage response;

            // Read the contents of the specified local image
            // into a byte array.
            byte[] byteData = GetImageAsByteArray(imageFilePath);

            // Add the byte array as an octet stream to the request body.
            using (ByteArrayContent content = new ByteArrayContent(byteData))
            {
                // This example uses the "application/octet-stream" content type.
                // The other content types you can use are "application/json"
                // and "multipart/form-data".
                content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                // Asynchronously call the REST API method.
                response = await client.PostAsync(uri, content);
            }

            // Asynchronously get the JSON response.
            string contentString = await response.Content.ReadAsStringAsync();

            // Display the JSON response.
            Console.WriteLine("\nResponse:\n\n{0}\n",
                JToken.Parse(contentString).ToString());



            Rootobject r = JsonConvert.DeserializeObject<Rootobject>(contentString);

            foreach (Region region in r.regions)
            {
                foreach (Line line in region.lines)
                {
                    foreach (Word word in line.words)
                    {
                        Console.WriteLine(word.text);
                        Console.Write("");
                    }
                    Console.WriteLine();
                }





            }
        }
        catch (Exception e)
        {
            Console.WriteLine("\n" + e.Message);
        }
    }

    /// <summary>
    /// Returns the contents of the specified file as a byte array.
    /// </summary>
    /// <param name="imageFilePath">The image file to read.</param>
    /// <returns>The byte array of the image data.</returns>
    static byte[] GetImageAsByteArray(string imageFilePath)
    {
        // Open a read-only file stream for the specified file.
        using (FileStream fileStream =
            new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
        {
            // Read the file's contents into a byte array.
            BinaryReader binaryReader = new BinaryReader(fileStream);
            return binaryReader.ReadBytes((int)fileStream.Length);



        }


    }

}

标签: c#asp.netapiwebformsocr

解决方案


与其追逐 Web 表单,不如尝试使用 Blazor 和 .Net Core。您仍然可以重用现有的 C# 代码。此处的快速教程:Blazor 教程

启动一个新的 Blazor 应用程序(前提是您安装了 .Net 核心)就像从您选择的文件夹中的 powershell 运行以下命令之一一样简单。

//serverside (renders views on server and syncs to client) 
dotnet new blazorserver 

//clientside (c# is transpiled to webassembly and runs purely in client browser - still finicky but YMMV) 
dotnet new blazorwasm

您可以使用现有的工作项目作为学习新技术的跳板,让您快速启动并运行。

我已按照以下文章获取文件上传,您可以自定义示例以获取图像字节。blazor 输入文件


推荐阅读