2016-12-23 20 views
2

我试图从PHP脚本调用Google Cloud Vision。另外,我想从网页获取图像数据,并尝试将图像数据从JavaScript发送到PHP脚本。我得到了“图像注释器::错误的图像数据:图像处理错误!”来自Google Cloud Vision

但是,我收到了Google Cloud Vision的错误消息。

{ 
    "responses": [ 
    { 
     "error": { 
      "code": 3, 
     "message": "image-annotator::Bad image data.: Image processing error!" 
     } 
    }] 
} 

这是我的JavaScript代码片段。

var b64 = ImageToBase64(img, "image/jpeg"); 
    $.ajax ({ 
     type: "POST", 
     url: "php/ocr.php", 
     data: "data=" + b64, 
     contentType: false, 
     processData: false, 

     // Method when calling ocr.php was successed. 
     success: function(data, dataType) 
     { 
      // Show the data 
      console.log(data); 
      $("#source_text").html(data); 
      var text = "It is snow today"; 
      translateText(text); 
     }, 
     // Method when calling ocr.php was failed. 
     error: function(XMLHttpRequest, textStatus, errorThrown) 
     { 
      // Display error message. 
      alert('Error : ' + errorThrown); 
     } 
    }); 

function ImageToBase64(img, mime_type) { 
    // New Canvas 
    var canvas = document.createElement('canvas'); 
    canvas.width = img.width; 
    canvas.height = img.height; 
    // Draw Image 
    var ctx = canvas.getContext('2d'); 
    ctx.drawImage(img, 0, 0); 
    // To Base64 
    return canvas.toDataURL(mime_type); 
} 

而我的PHP脚本如下。

$api_key = "my-api-key" ; 

$image_data = $_POST["data"]; 
$image = base64_decode($image_data); 

// Feature Type 
$feature = "TEXT_DETECTION"; 

$param = array("requests" => array()); 
// $item["image"] = array("content" => base64_encode($image)); 
$item["image"] = array("content" => $image_data); 
$item["features"] = array(array("type" => $feature, "maxResults" => 1)); 
$param["requests"][] = $item; 

$json = json_encode($param); 

$curl = curl_init() ; 
curl_setopt($curl, CURLOPT_URL, "https://vision.googleapis.com/v1/images:annotate?key=" . $api_key); 
curl_setopt($curl, CURLOPT_HEADER, true); 
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); 
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_TIMEOUT, 15); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $json); 
$res1 = curl_exec($curl); 
$res2 = curl_getinfo($curl); 
curl_close($curl); 

$json = substr($res1, $res2["header_size"]); 
$array = json_decode($json, true); 

echo $json; 

我猜想图像处理一定是错的。但我不知道该怎么办。 你能给我一个建议吗?

+0

你有没有最终搞清楚你的问题是什么?我遇到了同样的错误。 – harasho

回答

0

您可以使用谷歌PHP API客户端库与ServiceAccount和OAuth 2

0

我不得不重新编码在PHP上的图像:

// re-encode image 
    $data = str_replace('data:image/png;base64,', '', $imageData); 
    $data = base64_decode($data);