Skip to content

Instantly share code, notes, and snippets.

@derekantrican
Created May 23, 2022 18:42
Show Gist options
  • Save derekantrican/ad471bd88aa1eb12b5a0ce66e87383e1 to your computer and use it in GitHub Desktop.
Save derekantrican/ad471bd88aa1eb12b5a0ce66e87383e1 to your computer and use it in GitHub Desktop.
.NET 6 & minimal code to perform OCR on a image using ocr.space
using Newtonsoft.Json;
//Add your filepath & ocr.space key below
string ocr = await DoOCR("screenshot.jpg", "OCR.SPACE API KEY");
Console.WriteLine(ocr);
static async Task<string> DoOCR(string fileName, string apikey)
{
string resp = null;
try
{
HttpClient httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(5);
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(apikey), "apikey");
form.Add(new StringContent("eng"), "language");
form.Add(new StringContent("2"), "ocrengine");
form.Add(new StringContent("true"), "scale");
form.Add(new StringContent("true"), "istable");
byte[] imageData = File.ReadAllBytes(fileName);
form.Add(new ByteArrayContent(imageData, 0, imageData.Length), "image", "image.jpg");
HttpResponseMessage response = await httpClient.PostAsync("https://api.ocr.space/Parse/Image", form);
resp = await response.Content.ReadAsStringAsync();
dynamic ocrResult = JsonConvert.DeserializeObject<dynamic>(resp);
if (ocrResult.OCRExitCode == 1)
{
string results = "";
foreach (var parsedResult in ocrResult.ParsedResults)
{
results += parsedResult.ParsedText;
}
return results;
}
else
{
Console.WriteLine($"OCR error: {ocrResult.ErrorMessage[0]}");
}
}
catch (Exception exception)
{
Console.WriteLine($"OCR exception: {exception.Message}\n{exception.StackTrace}");
Console.WriteLine($"OCR response: {resp}");
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment