public class HomeController : Controller
{
private Microsoft.AspNetCore.Hosting.IHostingEnvironment _environment;
public HomeController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
{
_environment = hostingEnvironment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Index(IFormFile file)
{
if (file == null)
{
ModelState.Clear();
ModelState.AddModelError("file", "Please select file first.");
return View("Index");
}
var key = "pass your key here";
var endPoint = "https://write your end point here";
ComputerVisionClient client = Authenticate(endPoint, key);
if (file.Length > 0)
{
var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "UploadedFiles"));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
using (var fileStream = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
var contentPath = _environment.ContentRootPath + "\\UploadedFiles\\";
var fileName = contentPath + file.FileName;
var text = await ReadImage(client, fileName);
if (string.IsNullOrEmpty(text))
text = "No text found.";
ViewBag.extractText = text;
FileInfo fileInfo = new FileInfo(fileName);
if (fileInfo.Exists)//check file exsit or not
{
fileInfo.Delete();
}
return View("Index");
}
public ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public async Task<string> ReadImage(ComputerVisionClient client, string localFile)
{
StringBuilder sb = new StringBuilder();
// Read text from URL
var textHeaders = await client.ReadInStreamAsync(System.IO.File.OpenRead(localFile));
// After the request, get the operation location (operation ID)
string operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
// Extract the text
ReadOperationResult results;
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
}
while ((results.Status == OperationStatusCodes.Running ||
results.Status == OperationStatusCodes.NotStarted));
var textUrlFileResults = results.AnalyzeResult.ReadResults;
foreach (ReadResult page in textUrlFileResults)
{
foreach (Line line in page.Lines)
{
sb.AppendLine(line.Text);
}
}
return sb.ToString();
}
}