问题
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?
回答1:
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
.
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
来源:https://stackoverflow.com/questions/43826777/base-64-image-to-ocr-space-api-ionic-2