Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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