OCR with Laravel and Google Cloud Vision.

ocr

In this tutorial, I will show you how to easily read text from images directly from your Laravel application. We will be making use of Google’s Cloud Vision API. This robust API allows us to perform other forms of image analysis that I will not cover in this post.

Everyone wondered how you could read text from an image? Maybe you’re building a traffic application where you need to read plate numbers from snapshots of cars or something as simple as extracting text from snapshots of PDF files.

So let’s start our tutorial with below steps:

Step 1: Create an account with Google cloud console and it’s API.

An account with Google and a Google cloud console project and it’s API. So you can Create and Managing Projects to learn how to set up a Google cloud console project. Make sure to enable the vision API for your project. Click Before you begin to see how.

A Using API Keys for your Google cloud console project. Click Using API Keys to see how to get your API key.


Step 2: Install a composer in your Project.

So open your terminal and runs the below code:

composer require wapnen/google-cloud-vision-php

After running the command you have to open .env file in your project and put the below code.

GOOGLE_CLOUD_KEY= your api key

Now running your server so open your terminal and put below code.

php artisan serve

Step 3: Create a Controller and web routes

In this step, we have to create a controller file in your local directory. open your terminal and put below code.

php artisan make:controller OcrController

Now open your routes file routes/web.php and put the below code.

Route::get('/ocr', 'OcrController@displayForm');
Route::post('/ocr', 'OcrController@ocrImage');

So we have to create two methods displayForm & ocrImage.

  • displayForm => This method to show the upload form
  • ocrImage => This method used with the help of upload image to check image OCR or not.

So open your Controller file OcrController.php and put the below code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GoogleCloudVision\GoogleCloudVision;
use GoogleCloudVision\Request\AnnotateImageRequest;

class OcrController extends Controller{
    public function displayForm(){
        return view('ocr');
    }
    public function ocrImage(Request $request){
	    if($request->file('image')){
	    	//convert image to base64
			$image = base64_encode(file_get_contents($request->file('image')));
			//Sending image for OCR server
			$request = new AnnotateImageRequest();
			$request->setImage($image);
			$request->setFeature("TEXT_DETECTION");
			$gcvRequest = new GoogleCloudVision([$request],  env('GOOGLE_CLOUD_KEY'));
			//Send Request to check image OCR or not through annotate
			$response = $gcvRequest->annotate();
			echo json_encode(["description" => $response->responses[0]->textAnnotations[0]->description]);
	    }
    }
}

Now let me explain this tutorial main part. The methods of code above create a single AnnotateImageRequest() object. the setImage() function takes a base64encoded image string as a parameter. This is the image to be annotated. the setFeature() function sets the type of Google Cloud Vision API detection to perform on the image. Since we are performing OCR, we only need to set the TEXT_DETECTION feature. You can set as many features as you want by calling the setFeature() function on the AnnotateImageRequest() and passing the corresponding feature. Check the Google cloud vision API reference for available features.

Now, Our second The GoogleCloudVision() object takes an array of AnnotateImageRequest() objects as the first parameter and your API key as a second parameter. Finally, we called the annotate() function to send the image to google cloud where image checks the OCR.


Step 4: Create a blade file

In this part, we have to create a blade file where it will use to upload an image and save it ocr.blade.php, so create a file and put the below code.

@extends('layouts.app')
@section('content')
<div class="container">
   <div class="row justify-content-center">
      <div class="col-md-8">
         <div class="card">
            <div class="card-header">{{ __('Optical Character Recognition | Image OCR') }}</div>
               <div class="card-body">
                  <form role="form" method="POST" action="/ocr" enctype="multipart/form-data">
                     @csrf
                     <div class="form-group row">
                        <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('Upload image') }}</label>
                        <div class="col-md-6">
                           <input id="image" type="file" class="form-control{{ $errors->has('image') ? ' is-invalid' : '' }}" name="image" value="{{ old('image') }}" required autofocus>
                           @if ($errors->has('image'))
                           <span class="invalid-feedback">
                           <strong>{{ $errors->first('image') }}</strong>
                           </span>
                           @endif
                        </div>
                     </div>
                     <div class="form-group row mb-0">
                        <div class="col-md-8 offset-md-4">
                           <button type="submit" class="btn btn-primary">
                           {{ __('Submit') }}
                           </button>
                        </div>
                     </div>
                  </form>
               </div>
         </div>
      </div>
   </div>
</div>
@endsection

Here the image to upload:


Upload Image to check:

Upload an image containing text and submit. Upload image with text to check OCR or not. If you have don’t image with text so download images here:



Now you have to open your browser and put below URL:

http://127.0.0.1:8000/googleCaptcha

About Dhaval Shah

My name is Dhaval Shah. I'm a Laravel developer. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress, and Bootstrap.
Follow me on Github / Linkedin

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!