出现此错误的核心原因是图像数据过大(超过6M),建议适当压缩图片,压缩比在60%以上识别率不受影响,反而效率更快更高。
以下的小程序等纯前端的图片压缩方式,可以参考:
压缩后转 Base64 调用(以营业执照识别接口为例,其他图像识别接口均相同),以下是完整、可用的方案:
步骤:
用户选择图片
使用 canvas 压缩(控制尺寸和质量)
读取压缩后临时文件 → 转为 纯 Base64 字符串
调用 TianAPI 的 OCR 接口,传入 key 和 img
(建议额外增加图片大小的判断,避免图片本身不清晰的情况下再次压缩影响识别率)
Page({
async chooseAndRecognize() {
try {
// 1. 选择图片
const { tempFilePaths } = await wx.chooseImage({ count: 1 });
const src = tempFilePaths[0];
// 2. 压缩图片(最大边 1080,质量 0.7)
const compressedPath = await this.compressImage(src, 1080, 0.7);
// 3. 转为纯 Base64(不带 data:image/... 前缀!)
const pureBase64 = this.getPureBase64(compressedPath);
// 4. 调用 TianAPI 营业执照识别接口
const res = await wx.request({
url: 'https://apis.tianapi.com/ocrbusiness/index',
method: 'POST',
data: {
key: '你的APIKEY', // 替换为你在 TianAPI 注册后获得的 key
img: pureBase64 // 注意:不是 imgurl,且不能带前缀
},
header: {
'content-type': 'application/x-www-form-urlencoded'
}
});
if (res.data.code === 200) {
console.log('识别成功:', res.data.result);
wx.showToast({ title: '识别成功', icon: 'success' });
// 可在此处理 result 中的 name, creditno, legalperson 等字段
} else {
wx.showToast({ title: res.data.msg || '识别失败', icon: 'none' });
}
} catch (err) {
console.error('操作失败:', err);
wx.showToast({ title: '处理失败', icon: 'none' });
}
},
// 压缩图片(返回临时路径)
compressImage(src, maxSize = 1080, quality = 0.7) {
return new Promise((resolve, reject) => {
wx.getImageInfo({
src,
success: (imageInfo) => {
let { width, height } = imageInfo;
if (Math.max(width, height) > maxSize) {
if (width > height) {
height = (height * maxSize) / width;
width = maxSize;
} else {
width = (width * maxSize) / height;
height = maxSize;
}
}
const query = wx.createSelectorQuery().in(this);
query.select('#compressCanvas')
.fields({ node: true })
.exec((res) => {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
const dpr = wx.getSystemInfoSync().pixelRatio;
canvas.width = width * dpr;
canvas.height = height * dpr;
const img = canvas.createImage();
img.onload = () => {
ctx.scale(dpr, dpr);
ctx.drawImage(img, 0, 0, width, height);
canvas.toTempFilePath({
fileType: 'jpg',
quality,
success: (tmp) => resolve(tmp.tempFilePath),
fail: reject
});
};
img.src = src;
});
},
fail: reject
});
});
},
// 获取纯 Base64(无 data URI 前缀)
getPureBase64(filePath) {
const fs = wx.getFileSystemManager();
const buffer = fs.readFileSync(filePath); // 默认返回 ArrayBuffer
const base64 = wx.arrayBufferToBase64(buffer);
return base64; // 直接返回纯 base64 字符串
}
});同时在: WXML 中添加隐藏 canvas:
<canvas type="2d" id="compressCanvas" style="width:0;height:0;position:absolute;left:-9999px;"></canvas>
使用手机后置摄像头拍照测试,如果没有出现code=>290错误提示就说明成功了。