1.申请接口权限
https://developers.weixin.qq.com/community/servicemarket/detail/000ce4cec24ca026d37900ed551415
2.OCR接口官方文档
3.本实例的云函数
4.前端代码:
<template>
<view>
<view class="box">
<button class="btn" type="primary" @click="textOcr">选择小于2M的图片</button>
</view>
<scroll-view class='textbox' scroll-y="true" >
<textarea v-model="text1" maxlength="-1" auto-height="true" />
</scroll-view>
<view class="box2">
<button class="btn2" type="primary" @click="copyAll">复制全部</button>
<button class="btn2" type="primary" @click="clearAll">清空全部</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
text1: ''
}
},
methods: {
//文字识别
textOcr() {
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album','camera'],
success: (res) => {
let filePath = res.tempFilePaths[0]
let fileSize = res.tempFiles[0].size
console.log(fileSize)
if (fileSize > 2000000) { //大于3m
wx.showToast({
title: '图片不能大于2M',
icon: 'none',
duration: 2000
})
return
} else {
uni.showLoading({
title: '处理中...'
})
wx.cloud.uploadFile({ //上传文件到云存储
filePath: filePath, // 本地文件路径
cloudPath: 'ocrImages/'+Date.now() + '.jpg', //保存在云端的路径及文件名(这里以时间戳命名)
success: (res) => {
let fileID = res.fileID //云端返回的fileID
wx.cloud.getTempFileURL({ //以fileID获取云存储文件的链接
fileList: [fileID],
success: (res) =>{
let tempFileURL = res.fileList[0].tempFileURL //云存储文件的链接
wx.cloud.callFunction({ //调用云函数
name: 'TXOcr',
data: {
imgUrl: tempFileURL
},
success:(res) => {
console.log(res)
if(res.result.errCode == 0 ) { //识别成功
let result = res.result.items //云端返回的结果
if (result.length > 0) {
let arr = []
for (let i = 0; i < result.length; i++) {
arr += result[i].text + "\n" // 这个"\n"功能是换行
}
//console.log(arr)
this.text1 = arr
}
}else{ //识别出错
console.log(res.result.errMsg)
}
},
fail: (err) => {
console.log(err)
},
complete:() => {
uni.hideLoading()
}
})
},
fail:(err) =>{
console.log(err)
}
})
},
fail:(err) => {
console.log(err)
}
})
}
}
})
},
copyAll() {
let that = this
wx.setClipboardData({
data: that.text1,
success: (res) => {
wx.showToast({
title: '复制成功',
icon: 'success'
})
}
})
},
clearAll() {
this.text1 = ''
}
}
}
</script>
<style>
.box{
display: flex;
width: 98%;
flex-direction: column;
align-items: center;
justify-content: center;
}
.btn{
margin: 10px;
width: 200px;
}
.textbox{
width: 94%;
height: 900rpx;
border: 1rpx;
border-style: solid;
margin-left: 10px;
}
textarea{
width: 98%;
margin-left: 3px;
}
.box2{
display: flex;
width: 98%;
flex-direction: row;
align-items: center;
justify-content: center;
}
.btn2{
margin: 10px;
width: 100px;
}
</style>
5.效果图
以下是用于识别的图片