Skip to content

Instantly share code, notes, and snippets.

@justinyoo
Created March 27, 2017 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinyoo/a3088d9a0f85dacf3ec94c109c8138ac to your computer and use it in GitHub Desktop.
Save justinyoo/a3088d9a0f85dacf3ec94c109c8138ac to your computer and use it in GitHub Desktop.
Implementing OCR Using Azure Cognitive Services with HTML5 Media Capture API
[Route("api")]
public class ApiController : Controller
{
...
[Route("ocr")]
[HttpPost]
public async Task<IActionResult> ProcessText(IFormFile file)
{
// Retrives the file data from Request.Form instance,
// in case the file instance is null
if (file == null)
{
file = this.Request.Form.Files.FirstOrDefault();
}
OcrResults result;
string imagePath;
using (var stream = file.OpenReadStream())
{
// Puts the API key here
var client = new VisionServiceClient("[VISION_API_KEY_HERE]");
try
{
// Gets the OCR result from Cognitive Services Vision API
result = await client.RecognizeTextAsync(stream, languageCode: "en", detectOrientation: true);
// Gets the image data back
using (var ms = new MemoryStream())
{
await file.CopyToAsync(ms).ConfigureAwait(false);
var base64 = Convert.ToBase64String(ms.ToArray());
var value = $"data:{file.ContentType};base64,{base64}";
imagePath = value;
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
var settings = new JsonSerializerSettings() { Formatting = Formatting.Indented };
return Json(new { Result = result, ImagePath = imagePath }, settings);
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment