I’m currently working on a project that requires extracting text from images of variable quality. I’m doing quick prototypes using PHP and Laravel, but I’ve found the documentation for accomplishing this a bit lacking. After working on it for a bit, I figured out a really simple solution and am sharing in case it helps anyone else.

This sample will send the image to the API as a blob instead of using a URL. I had tried Base64 encoding it without any luck. I discovered that using Imagick was the easiest way to make this work so the sample relies on that.

Fire up terminal and add a requirement for aws/aws-sdk-php:

composer require aws/aws-sdk-php

Add keys for your AWS access keys and region to your .ENV file:

AWS_REGION=YOUR_REGION
AWS_SECRET_ACCESS_KEY=ENTER_YOUR_KEY
AWS_ACCESS_KEY_ID=ENTER_YOUR_KEY

Create a controller, add the snippet below, and create a route to the controller. Check the URL and you should have a dump showing the array returned from AWS with all the text, bounding boxes, and information.

        //Build config array for AWS variables
        $config = array(
            'region' => env('AWS_REGION'),
            'version' => 'latest',
            'credentials' => array(
                'key' => env('AWS_KEY'),
                'secret' => env('AWS_SECRET')
            )
        );

        //Replace with path to image or uploaded image.         
        $path = '{path to image.jpg}';

        $image = new Imagick($path);
        $imdata = $image->getImageBlob();

        $client = new RekognitionClient($config);

        $result = $client->detectText([
            'Image' => ['Bytes' => $imdata],
        ]);
        
        //Dump Result
        dd($result);
There are currently no comments.

Leave a Reply