Q&A
いつもお世話になっております。
今、PHPスクリプトからGoogle Cloud Visionを呼び出す処理を作成しています。画像はWebページからJavaScriptでPHPに送信したいと思っています。しかし、encode周りではないかと思うのですが、Google Cloud Vision側から以下のエラーが返ってきてしまいます。
JSON
1{ 2 "responses": [ 3 { 4 "error": { 5 "code": 3, 6 "message": "image-annotator::Bad image data.: Image processing error!" 7 } 8 }] 9}
PHPに画像を送るJavaScriptプログラムは以下の通りです。
JavaScript
1 var b64 = ImageToBase64(img, "image/jpeg"); 2 $.ajax ({ 3 type: "POST", 4 url: "php/ocr.php", 5 data: "data=" + b64, 6 contentType: false, 7 processData: false, 8 9 // Method when calling ocr.php was successed. 10 success: function(data, dataType) 11 { 12 // Show the data 13 console.log(data); 14 $("#source_text").html(data); 15 var text = "It is snow today"; 16 translateText(text); 17 }, 18 // Method when calling ocr.php was failed. 19 error: function(XMLHttpRequest, textStatus, errorThrown) 20 { 21 // Display error message. 22 alert('Error : ' + errorThrown); 23 } 24 }); 25 26function ImageToBase64(img, mime_type) { 27 // New Canvas 28 var canvas = document.createElement('canvas'); 29 canvas.width = img.width; 30 canvas.height = img.height; 31 // Draw Image 32 var ctx = canvas.getContext('2d'); 33 ctx.drawImage(img, 0, 0); 34 // To Base64 35 return canvas.toDataURL(mime_type); 36}
そして、Google Cloud Vision APIを呼び出すPHPスクリプトは以下の通りです。
PHP
1$api_key = "my-api-key" ; 2 3$image_data = $_POST["data"]; 4$image = base64_decode($image_data); 5 6// Feature Type 7$feature = "TEXT_DETECTION"; 8 9$param = array("requests" => array()); 10// $item["image"] = array("content" => base64_encode($image)); 11$item["image"] = array("content" => $image_data); 12$item["features"] = array(array("type" => $feature, "maxResults" => 1)); 13$param["requests"][] = $item; 14 15$json = json_encode($param); 16 17$curl = curl_init() ; 18curl_setopt($curl, CURLOPT_URL, "https://vision.googleapis.com/v1/images:annotate?key=" . $api_key); 19curl_setopt($curl, CURLOPT_HEADER, true); 20curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); 21curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); 22curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 23curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 24curl_setopt($curl, CURLOPT_TIMEOUT, 15); 25curl_setopt($curl, CURLOPT_POSTFIELDS, $json); 26$res1 = curl_exec($curl); 27$res2 = curl_getinfo($curl); 28curl_close($curl); 29 30$json = substr($res1, $res2["header_size"]); 31$array = json_decode($json, true); 32 33echo $json;
PHPスクリプトで固定の画像ファイルをGoogle Cloud Visionに送ったら正常に値が取得できたので、おそらく画像データが正しく処置できていないのではないかと思うのですが、行き詰まってしまいました。
お知恵を拝借できればと思います。
よろしくお願いします。
回答1件
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。