windowcapture
исходный код / Ocr/Program.cs

Program.cs

67 строк · 2,508 байт · модуль Ocr
 1using System;
 2using System.IO;
 3using System.Text;
 4using System.Threading.Tasks;
 5using Windows.Globalization;
 6using Windows.Graphics.Imaging;
 7using Windows.Media.Ocr;
 8using Windows.Storage;
 9
10namespace WC.OcrHelper
11{
12    /// <summary>
13    /// WC.Ocr &lt;imagePath&gt; [lang]  →  prints recognized text to stdout (UTF-8), exit 0.
14    /// Uses the built-in Windows OCR engine. lang is a BCP-47 tag ("ru", "en"); if omitted or
15    /// unavailable it falls back to the user's profile languages. Exit codes: 0 ok, 1 OCR error,
16    /// 2 bad args/file, 3 no OCR engine/language installed.
17    /// </summary>
18    internal static class Program
19    {
20        private static async Task<int> Main(string[] args)
21        {
22            try { Console.OutputEncoding = Encoding.UTF8; } catch { }
23
24            if (args.Length < 1)
25            {
26                Console.Error.WriteLine("usage: WC.Ocr <imagePath> [lang]");
27                return 2;
28            }
29            string path;
30            try { path = Path.GetFullPath(args[0]); } catch { Console.Error.WriteLine("bad path"); return 2; }
31            if (!File.Exists(path)) { Console.Error.WriteLine("file not found: " + path); return 2; }
32            string lang = args.Length > 1 ? args[1] : null;
33
34            try
35            {
36                StorageFile file = await StorageFile.GetFileFromPathAsync(path);
37                SoftwareBitmap bitmap;
38                using (var stream = await file.OpenReadAsync())
39                {
40                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
41                    bitmap = await decoder.GetSoftwareBitmapAsync();
42                }
43
44                OcrEngine engine = null;
45                if (!string.IsNullOrEmpty(lang))
46                {
47                    try { engine = OcrEngine.TryCreateFromLanguage(new Language(lang)); } catch { }
48                }
49                if (engine == null) engine = OcrEngine.TryCreateFromUserProfileLanguages();
50                if (engine == null)
51                {
52                    Console.Error.WriteLine("no OCR engine for the requested/profile language");
53                    return 3;
54                }
55
56                OcrResult result = await engine.RecognizeAsync(bitmap);
57                Console.Out.Write(result.Text ?? "");
58                return 0;
59            }
60            catch (Exception ex)
61            {
62                Console.Error.WriteLine("OCR error: " + ex.Message);
63                return 1;
64            }
65        }
66    }
67}