【发布时间】:2020-08-17 03:16:24
【问题描述】:
我正在尝试捕获桌面图像的一部分,然后使用 tesseract.exe 运行它,而无需将捕获的图像作为文件写入磁盘。 但是,下面的代码给了我一个错误或者一个过程不会结束。请帮忙?
Bitmap bmp=capture_and_crop();
using (Process process = new Process())
{
process.StartInfo.FileName = ts5path+"tesseract.exe";
process.StartInfo.Arguments = "stdin" + " stdout -l " + language + " --psm " + PSM_setting + " -c preserve_interword_spaces=1";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
process.Start();
BinaryWriter writer = new BinaryWriter(process.StandardInput.BaseStream);//line1. I get error here : standardIn has not been redirected, when I move these 2 lines above process.Start().
bmp.Save(writer.BaseStream, System.Drawing.Imaging.ImageFormat.Bmp);//line2.
//If these lines stay here there will be no redirection exception but this process will never end...
StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();
addtr1.str = output;
process.WaitForExit();
}
【问题讨论】:
-
您的问题是检测进程何时完成。在进程关闭之前,WaitForExit 不会变为真。应用程序是否返回结果? ReadToEnd 必须在一个循环中,因为它会立即返回。您正在读取流并且 ReadToEnd 读取到流的末尾。如果应用程序以返回结束,您可以改用 ReadLine()。如果应用程序保持打开状态,那么 WaitForExit 应该被消除,那么代码应该可以工作,除非应用程序在 StandardOutput 上没有返回(应用程序可能有一个 '\0' 而不是返回)。
-
如果我不使用 stdIn ,那么这段代码可以完美运行。但是,这意味着我必须将图像文件保存到磁盘然后使用它而不是标准输入。问题是如何让它与标准输入一起工作。
-
当您保存到文件时,窗口会关闭流,因此一切正常。您正在正确写入数据然后挂起,因为您没有检测到应用程序何时完成。
-
我删除了 WaitForExit 并将 ReadToEnd 更改为 ReadLine() 但程序仍然挂起。然后,当我将 BinaryWriter 编写器部分移动到上述 process.start 时,它会导致 'System.InvalidOperationException: StandardIn has not been redirected.'
-
您必须查看响应并查看结束字符。它可能是 null 或者不是 windows 返回 '\n' 它可能只是一个 '\r'。
标签: c# process bitmap tesseract stdin