3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

どうしてもWPFのWindows10OCRがフォームで使いたい

Last updated at Posted at 2025-02-21

環境はVisual Studio 2022です
色々ドハマリしすぎてヤケクソになっていたので色々お許しを

using System.Drawing.Imaging;
using System.IO;
using Windows.Media.Ocr;

namespace OCRTest;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        OcrWin10();
    }

    public async Task OcrWin10()
    {
        var Stream = new MemoryStream();
        var Image = System.Windows.Forms.Clipboard.GetImage();
        if (Image == null)
        {
            label1.Text = "画像ファイルがグリップボードにありません";
            return;
        }
        Image.Save(Stream, ImageFormat.Png);
        var RandomStream = WindowsRuntimeStreamExtensions.AsRandomAccessStream(Stream);
        var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(RandomStream);
        OcrEngine ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
        var OcrResult = await ocrEngine.RecognizeAsync(await decoder.GetSoftwareBitmapAsync());
        label1.Text = OcrResult.Text;
    }
}

クリップボードの画像を取得してラベルにOCR結果を表示するというものです
Microsoft.Windows.CsWinRTをnugetから落としまくってください
https://www.nuget.org/packages/Microsoft.Windows.CsWinRT/2.2.0?_src=template

おまけ

bufferやunsafeコードを使ってる方々がいっぱいいたんですけど
image.png
https://learn.microsoft.com/ja-jp/windows/uwp/audio-video-camera/imaging#create-or-edit-a-softwarebitmap-programmatically
Bufferが取れん爆破したるぞとか思っていたら
image.png
なんか二つおんなじ名前のブツが出てきたり(Bufferが取れるのは下のXamlの方)
unsafeはコピペで使うの怖いし...

丸々半日掛かってようやく書けた...
image.png
私が使いたかった用途だと精度が低くて使えなかった。私の半日...
Win10標準機能のOcrはもっと別の用途だと使えるのかもしれないが、ちっちゃめのスクショを読み取るのはあまりに無謀だったようだ

3
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?