Error de despliegue de OcrInternals en aplicaciones x86

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronTesseract.ReadScreenShot() se ejecuta a través del pipeline AdvancedScan de IronOCR, que solo es compatible con un proceso Windows x64. Llamarlo desde una aplicación x86 falla con un error de implementación OcrInternals, incluso cuando el paquete IronOcr.Extensions.AdvancedScan está instalado.

Error while reading a screenshot, Error while deploying OcrInternals for IronOcr:
'Unable to locate 'OcrInternals' in
...\bin\Debug\runtimes\win-x86\native,
...\bin\Debug\runtimes\win.6.2-x86\native,
...\bin\Debug\runtimes\win.6-x86\native,
...\bin\Debug\,
...
nor in an embedded resource.'
Please install the NuGet Package 'IronOcr.Extension.AdvancedScan' when using IronOcr on Windows.
[Issue Code IRONOCR-OCRINTERNALS-DEPLOYMENT-ERROR-WIN]

La falla se presenta en la llamada ReadScreenShot() en sí:

var ocr = new IronOcr.IronTesseract();
using (var input = new IronOcr.OcrInput())
{
    input.LoadImage("Step_1-5.jpg");
    var result = ocr.ReadScreenShot(input);
    Console.WriteLine(result.Text);
}
var ocr = new IronOcr.IronTesseract();
using (var input = new IronOcr.OcrInput())
{
    input.LoadImage("Step_1-5.jpg");
    var result = ocr.ReadScreenShot(input);
    Console.WriteLine(result.Text);
}
Imports IronOcr

Dim ocr As New IronTesseract()
Using input As New OcrInput()
    input.LoadImage("Step_1-5.jpg")
    Dim result = ocr.ReadScreenShot(input)
    Console.WriteLine(result.Text)
End Using
$vbLabelText   $csharpLabel

Los componentes nativos de AdvancedScan de los que depende ReadScreenShot() no son compatibles dentro de un proceso x86. Se requiere instalar IronOcr.Extensions.AdvancedScan, pero no cambia la arquitectura del proceso anfitrión, por lo que la llamada aún no puede ejecutarse bajo x86.

PrecauciónInstalar AdvancedScan no hace que ReadScreenShot() funcione en un proceso x86. El proceso que lo llama debe ejecutarse como x64.

Solución

Opción 1: Apuntar a x64 directamente

La solución más limpia es cambiar el objetivo de la plataforma del proyecto a x64. En Visual Studio:

  1. Haz clic derecho en el proyecto y selecciona Propiedades.
  2. Abre la pestaña Compilación.
  3. Configura Objetivo de plataforma en x64.
  4. Desmarca Preferir 32-bit.
  5. Reconstruir y ejecutar.

Con el proceso anfitrión ejecutándose como x64, ReadScreenShot() se ejecuta en un entorno compatible.

Opción 2: Mantén la aplicación x86 y llama a un proceso auxiliar x64

Cuando la aplicación principal debe permanecer x86, mueve solo la operación OCR a un pequeño proceso auxiliar x64 y llámalo desde la aplicación existente. La estructura se ve así:

MainWinForms.x86
  - .NET Framework Windows Forms app
  - Platform target: x86
  - Does not run ReadScreenShot() directly
  - Calls the x64 helper process
OcrHelper.x64
  - .NET Framework Console app
  - Platform target: x64
  - References IronOCR
  - References IronOcr.Extensions.AdvancedScan
  - Runs Ocr.ReadScreenShot()
  - Returns the OCR result to the main app

La aplicación x86 permanece intacta mientras AdvancedScan se ejecuta donde es compatible.

Llamando al auxiliar desde la aplicación x86

Inicie el asistente con ProcessStartInfo y lea su salida:

using System;
using System.Diagnostics;
using System.IO;
public static class OcrHelperClient
{
    public static string ReadScreenshotWithHelper(string imagePath)
    {
        string helperExePath = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory,
            "OcrHelper.x64",
            "OcrHelper.x64.exe"
        );
        if (!File.Exists(helperExePath))
        {
            throw new FileNotFoundException("The OCR helper executable was not found.", helperExePath);
        }
        var startInfo = new ProcessStartInfo
        {
            FileName = helperExePath,
            Arguments = "\"" + imagePath + "\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        };
        using (var process = new Process())
        {
            process.StartInfo = startInfo;
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                throw new Exception("OCR helper failed: " + error);
            }
            return output;
        }
    }
}
using System;
using System.Diagnostics;
using System.IO;
public static class OcrHelperClient
{
    public static string ReadScreenshotWithHelper(string imagePath)
    {
        string helperExePath = Path.Combine(
            AppDomain.CurrentDomain.BaseDirectory,
            "OcrHelper.x64",
            "OcrHelper.x64.exe"
        );
        if (!File.Exists(helperExePath))
        {
            throw new FileNotFoundException("The OCR helper executable was not found.", helperExePath);
        }
        var startInfo = new ProcessStartInfo
        {
            FileName = helperExePath,
            Arguments = "\"" + imagePath + "\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        };
        using (var process = new Process())
        {
            process.StartInfo = startInfo;
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                throw new Exception("OCR helper failed: " + error);
            }
            return output;
        }
    }
}
Imports System
Imports System.Diagnostics
Imports System.IO

Public Module OcrHelperClient
    Public Function ReadScreenshotWithHelper(imagePath As String) As String
        Dim helperExePath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OcrHelper.x64", "OcrHelper.x64.exe")
        If Not File.Exists(helperExePath) Then
            Throw New FileNotFoundException("The OCR helper executable was not found.", helperExePath)
        End If

        Dim startInfo As New ProcessStartInfo With {
            .FileName = helperExePath,
            .Arguments = """" & imagePath & """",
            .UseShellExecute = False,
            .RedirectStandardOutput = True,
            .RedirectStandardError = True,
            .CreateNoWindow = True
        }

        Using process As New Process()
            process.StartInfo = startInfo
            process.Start()
            Dim output As String = process.StandardOutput.ReadToEnd()
            Dim error As String = process.StandardError.ReadToEnd()
            process.WaitForExit()

            If process.ExitCode <> 0 Then
                Throw New Exception("OCR helper failed: " & error)
            End If

            Return output
        End Using
    End Function
End Module
$vbLabelText   $csharpLabel

Redirigir tanto StandardOutput como StandardError permite al llamador capturar el texto reconocido y mostrar cualquier falla del código de salida del asistente.

string imagePath = @"C:\Images\Step_1-5.jpg";
string text = OcrHelperClient.ReadScreenshotWithHelper(imagePath);
Console.WriteLine(text);
string imagePath = @"C:\Images\Step_1-5.jpg";
string text = OcrHelperClient.ReadScreenshotWithHelper(imagePath);
Console.WriteLine(text);
Imports System

Dim imagePath As String = "C:\Images\Step_1-5.jpg"
Dim text As String = OcrHelperClient.ReadScreenshotWithHelper(imagePath)
Console.WriteLine(text)
$vbLabelText   $csharpLabel

Construyendo el auxiliar x64

Construya el asistente como una aplicación de consola x64 que haga referencia a IronOcr y IronOcr.Extensions.AdvancedScan. Lee la ruta de la imagen del primer argumento, ejecuta el OCR y escribe el resultado en @@--CODE-271@@:

using System;
using System.IO;
using IronOcr;
namespace OcrHelper.x64
{
    internal static class Program
    {
        private static int Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.Error.WriteLine("Missing image path argument.");
                    return 1;
                }
                string imagePath = args[0];
                if (!File.Exists(imagePath))
                {
                    Console.Error.WriteLine("Image file was not found: " + imagePath);
                    return 2;
                }
                string licenseKey = Environment.GetEnvironmentVariable("IRONOCR_LICENSE_KEY");
                if (!string.IsNullOrWhiteSpace(licenseKey))
                {
                    License.LicenseKey = licenseKey;
                }
                var ocr = new IronTesseract();
                using (var input = new OcrInput())
                {
                    input.LoadImage(imagePath);
                    var result = ocr.ReadScreenShot(input);
                    Console.WriteLine(result.Text);
                }
                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return 99;
            }
        }
    }
}
using System;
using System.IO;
using IronOcr;
namespace OcrHelper.x64
{
    internal static class Program
    {
        private static int Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.Error.WriteLine("Missing image path argument.");
                    return 1;
                }
                string imagePath = args[0];
                if (!File.Exists(imagePath))
                {
                    Console.Error.WriteLine("Image file was not found: " + imagePath);
                    return 2;
                }
                string licenseKey = Environment.GetEnvironmentVariable("IRONOCR_LICENSE_KEY");
                if (!string.IsNullOrWhiteSpace(licenseKey))
                {
                    License.LicenseKey = licenseKey;
                }
                var ocr = new IronTesseract();
                using (var input = new OcrInput())
                {
                    input.LoadImage(imagePath);
                    var result = ocr.ReadScreenShot(input);
                    Console.WriteLine(result.Text);
                }
                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return 99;
            }
        }
    }
}
Imports System
Imports System.IO
Imports IronOcr

Namespace OcrHelper.x64
    Friend Module Program
        Private Function Main(args As String()) As Integer
            Try
                If args.Length = 0 Then
                    Console.Error.WriteLine("Missing image path argument.")
                    Return 1
                End If

                Dim imagePath As String = args(0)
                If Not File.Exists(imagePath) Then
                    Console.Error.WriteLine("Image file was not found: " & imagePath)
                    Return 2
                End If

                Dim licenseKey As String = Environment.GetEnvironmentVariable("IRONOCR_LICENSE_KEY")
                If Not String.IsNullOrWhiteSpace(licenseKey) Then
                    License.LicenseKey = licenseKey
                End If

                Dim ocr As New IronTesseract()
                Using input As New OcrInput()
                    input.LoadImage(imagePath)
                    Dim result = ocr.ReadScreenShot(input)
                    Console.WriteLine(result.Text)
                End Using

                Return 0
            Catch ex As Exception
                Console.Error.WriteLine(ex.ToString())
                Return 99
            End Try
        End Function
    End Module
End Namespace
$vbLabelText   $csharpLabel

Códigos de salida distintos (1, 2, 99) permiten a la aplicación que llama distinguir un argumento faltante de un archivo faltante o una excepción inesperada.

Notas para uso en producción

El ejemplo utiliza stdout por simplicidad. Para producción, elige el método de comunicación que se ajuste a tu arquitectura. Las opciones incluyen:

  • Salida estándar y error estándar.
  • Archivos JSON temporales.
  • Tuberías nombradas.
  • Un punto final HTTP local.
  • Un servicio de Windows alojando la operación OCR x64.

Para llamadas pequeñas o ocasionales: lanzar el auxiliar bajo demanda suele ser suficiente. Para cargas de trabajo de alto volumen: un servicio auxiliar x64 que se ejecuta durante mucho tiempo tiende a ser más eficiente que generar un proceso por solicitud.

Consejos para depuración

Realiza estas verificaciones cuando el enfoque del auxiliar se comporte mal:

  • Confirme que la aplicación principal realmente necesita mantenerse en x86, y que Ocr.Read() no es suficiente para el escenario de captura de pantalla.
  • Verifique que ReadScreenShot() tenga éxito cuando se ejecuta directamente desde un proceso x64.
  • Construya el proyecto del asistente con Objetivo de plataforma: x64, y asegúrese de que la aplicación x86 nunca llame a ReadScreenShot() en sí misma.
  • Instale IronOcr.Extensions.AdvancedScan en el proyecto del asistente x64.
  • Comprueba que la ruta de la imagen pasada al auxiliar sea accesible por el proceso auxiliar.
  • Configure la clave de licencia de IronOCR en código, configuración de la aplicación o la variable de entorno IRONOCR_LICENSE_KEY.

Al publicar el asistente, copie toda la salida de la compilación, no solo la .exe. La carpeta de salida debe incluir todas las bibliotecas referenciadas y los archivos de runtime nativos generados por la compilación, o el auxiliar encontrará el mismo error de despliegue.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 6,136,090 | Versión: 2026.7 recién lanzado
Still Scrolling Icon

¿Aún desplazándote?

¿Quieres una prueba rápida? PM > Install-Package IronOcr
ejecuta una muestra y observa cómo tu imagen se convierte en texto buscable.