Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created June 12, 2020 23:03
Show Gist options
  • Select an option

  • Save JerryNixon/430b17bdd5d5973c2b001beb2a970a56 to your computer and use it in GitHub Desktop.

Select an option

Save JerryNixon/430b17bdd5d5973c2b001beb2a970a56 to your computer and use it in GitHub Desktop.
Calling OCRSDK by Abbyy from UWP. This is how you do it.
// create http cache
if (_cachedClient is null)
{
// create credntial for http client
var credentials = new Windows.Security.Credentials.PasswordCredential
{
UserName = _settingsService.AbbyyApplicationId,
Password = _settingsService.AbbyyPassword,
};
var handler = new HttpBaseProtocolFilter { ServerCredential = credentials, };
_cachedClient = new Windows.Web.Http.HttpClient(handler);
}
// set http client
var client = _cachedClient;
// call to process image
// read file as stream
var stream = await image.OpenStreamForReadAsync();
var file = new HttpStreamContent(stream.AsInputStream());
// build process image url
var url = $"{_settingsService.AbbyyServiceUrl}/{_processImageRelative}";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
throw new InvalidCastException($"OcrEndpoint is an invalid Uri: {url}");
}
// call the service
var response = await client.PostAsync(uri, file);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
var result = ParseJson(json);
// keep going until completed
while (!Equals(result.Status, "Completed"))
{
// wait for a time
await Task.Delay(1000);
// build get status url
url = $"{_settingsService.AbbyyServiceUrl}/{_taskStatusRelative}{result.TaskId}";
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
{
throw new InvalidCastException($"TaskStatus is an invalid Uri: {url}");
}
// call for status
var text = await client.GetStringAsync(uri);
result = ParseJson(text);
}
if (!Uri.TryCreate(result.Url, UriKind.Absolute, out uri))
{
throw new InvalidCastException($"Blob is an invalid Uri: {url}");
}
// download results
var xml = await client.GetStringAsync(uri);
// convert to object
var doc = new XmlDocument();
doc.LoadXml(xml);
// read all charParams
var chars = doc.GetElementsByTagName("charParams");
var elements = chars.OfType<XmlElement>();
// convert to letters
var letters = elements.Select(x => new
{
Rectangle = new System.Drawing.Rectangle(
int.Parse(x.Attributes["l"].Value),
int.Parse(x.Attributes["t"].Value),
int.Parse(x.Attributes["r"].Value) - int.Parse(x.Attributes["l"].Value),
int.Parse(x.Attributes["b"].Value) - int.Parse(x.Attributes["t"].Value)),
Text = x.InnerText,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment