-
-
Save justinyoo/a3088d9a0f85dacf3ec94c109c8138ac to your computer and use it in GitHub Desktop.
Implementing OCR Using Azure Cognitive Services with HTML5 Media Capture API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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