Last active
January 8, 2019 06:59
-
-
Save guruguruman/b2e16fa5612a1532911b20c44bdfd189 to your computer and use it in GitHub Desktop.
Google Cloud Vision API - Text detection
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
<?php | |
function fetchImageText($filePath = null, $apiKey = null) | |
{ | |
if (empty($filePath) || empty($apiKey)) { | |
return; | |
} | |
$json = json_encode(array( | |
"requests" => array( | |
array( | |
"image" => array( | |
"content" => base64_encode(file_get_contents($filePath)) | |
), | |
"features" => array( | |
array( | |
"type" => "TEXT_DETECTION", | |
"maxResults" => 100 | |
) | |
) | |
) | |
) | |
)); | |
$curl = curl_init(); | |
curl_setopt($curl, CURLOPT_URL, "https://vision.googleapis.com/v1/images:annotate?key=" . $apiKey); | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setopt($curl, CURLOPT_REFERER, 'https://cdMdXDMyqzBu.com/'); | |
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); | |
curl_setopt($curl, CURLOPT_HTTPHEADER, array( | |
"Content-Type: application/json" | |
)); | |
curl_setopt($curl, CURLOPT_TIMEOUT, 15); | |
curl_setopt($curl, CURLOPT_POSTFIELDS, $json); | |
$response = curl_exec($curl); | |
$data = json_decode($response, true); | |
curl_close($curl); | |
return $data["responses"][0]["fullTextAnnotation"]["text"]; | |
} | |
$distDir = './dist'; | |
if (!file_exists($distDir)) { | |
mkdir($distDir, 0775, true); | |
} | |
$sourceDir = $argv[1]; | |
$apiKey = $argv[2]; | |
if (strlen($apiKey) == 0) { | |
exit("No api key specified."); | |
} | |
if (strlen($sourceDir) == 0) { | |
exit("No resource path specified."); | |
} | |
$fileNames = preg_grep('/.(jpeg|jpg|png)/i', scandir($sourceDir)); | |
foreach ($fileNames as $fileName) { | |
$filePath = "${sourceDir}/${fileName}"; | |
$result = fetchImageText($filePath, $apiKey); | |
$distPath = "${distDir}/${substr($fileName, 0, strrpos($fileName, " . "))}.txt"; | |
file_put_contents($distPath, $result); | |
} | |
exit(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment