1

I am trying to send a base 64 Jpeg to an API for OCR analysis.

The API docs can be found here https://ocr.space/ocrapi

The code to save the Image is here:

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;
    });
 }

However I'm sure this is all fine as copying the base 64 string and sending via postman works fine.

This is how I send the string to the 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());
}

The base 64 string is passed to the val variable.

The given error is : "Not a valid base64 image. The accepted base64 image format is 'data:image/;base64,'."

Odd that it works fine in postman.... can anyone spot what i'm doing wrong?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
calmcalmuncle
  • 143
  • 1
  • 2
  • 16

1 Answers1

3

The problem is how you're sending over the data. If you look at the Postman collection with API call examples, you'll see that the base64image is being sent as form-data.

Postman call

But, as stated in this SO answer,

When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

So this code should work:

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("&");
    },
  })

Working demo: http://plnkr.co/edit/aPO4UGng7uaMbIqrzc7J

Community
  • 1
  • 1
Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
  • Fixed in a simpler way based on the code i already had, but your answer is very much correct! Thanks very much! – calmcalmuncle May 07 '17 at 01:53
  • @calmcalmuncle please consider upvoting answers if they were helpful, instead of saying thank you :) [More info](https://meta.stackexchange.com/questions/126180/is-it-acceptable-to-write-a-thank-you-in-a-comment) – sebaferreras May 07 '17 at 08:04