近期调试百度OCR模板识别API,一直返回如下错误:
data = {
isStructured = 0;
logId = 15724035...;
templateSign = 25f7f.....; };
"error_code" = 216201;
"error_msg" = "image format error";
参考https://ai.baidu.com/docs#/iOCR-General-API/top 总是失败,后经过与各种联系,终于发现问题并解决
原因是:
1.base64编码,带有\r\n ,需要去掉
2.不需要使用urlencode
另外图片大小需要限制
以下是我伪代码:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"AA" ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
NSData*imageData = [self jpgDataWithImage:imagesizeLimit:1024000];
NSData *data = UIImageJPEGRepresentation(image, 1.0f);
NSString *imageString = [imageData base64EncodedStringWithOptions:0];
// templateSign是模板 access_token是接口请求下来的(参考百度OCR的API文档)
NSDictionary *dic = @{@"image":imageString,@"templateSign":templateSign}; NSString *url = [NSString stringWithFormat:@"https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise?access_token=%@",access_token];
// 。。。。然后请求
- (NSData*)jpgDataWithImage:(UIImage*)imagesizeLimit:(NSUInteger)maxSize {
CGFloatcompressionQuality =1.0;
NSData*imageData =nil;
inti =0;
do{
imageData =UIImageJPEGRepresentation(image, compressionQuality);
compressionQuality -=0.1;
i +=1;
}while(i <3&& imageData.length> maxSize);
returnimageData;
}
网友评论