Base 64 Image to ocr.space API Ionic 2

时间:2017-05-07 00:50:30

标签: angularjs post ionic2 ocr angular-http

我正在尝试将基础64 Jpeg发送到API以进行OCR分析。

可在此处找到API文档https://ocr.space/ocrapi

保存图像的代码在这里:

takePicture() {
    Camera.getPicture({
        destinationType: Camera.DestinationType.DATA_URL,
        targetWidth: 1000,
        targetHeight: 1000,
        encodingType: Camera.EncodingType.JPEG,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit:true }).then((imageData)=>{
        this.base64Image = "data:image/jpeg;base64," + imageData;
    });
 }

但是我确定这很好,因为复制基本64字符串并通过邮递员发送工作正常。

这是我将字符串发送到API的方式。

post(val) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    headers.append('apikey', 'APIKEY');

    let data = 'base64Image=' + val;
    console.log(data);
    return this.http.post('http://api.ocr.space/parse/image', data, {headers: headers})
        .map(response => response.json());
}

将base 64字符串传递给val变量。

给定的错误是:"不是有效的base64图像。接受的base64图像格式为数据:image /; base64,'。"

奇怪的是它在邮递员中运作正常....有谁能发现我做错了什么?

1 个答案:

答案 0 :(得分:4)

问题在于您如何发送数据。如果您查看带有API调用示例的Postman collection,您会看到base64image被发送为form-data

Postman call

但是,如this SO answer中所述,

  

当我们想要将值发布为FORM帖子时,我们需要更改   序列化算法并使用内容类型发布数据,   “应用程序/ x WWW的形式进行了urlencoded”。

所以这段代码应该有效:

var headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
  'apikey': 'helloworld'
};
var data = {
  'base64image': 'data:image/png;base64,iVBORw0KGgoAAAANS...'
}

$http({
    method: 'POST',
    url: 'http://api.ocr.space/parse/image',
    headers: headers,
    data: data,
    transformRequest: function(obj) {
      var str = [];
      for (var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      return str.join("&");
    },
  })

工作演示:http://plnkr.co/edit/aPO4UGng7uaMbIqrzc7J