1.假设你已经完成了微信开发工具安装,注册了百度智能云开发管理申请免费的AK\SK 百度智能云-登录 (baidu.com)微信开放文档 (qq.com)
2.百度开发AK\SK转化为TOKEN
又或者百度开发文档查看
3.我的代码:
city.js
App({
onLaunch() {
this.get_access_token();
},
globalData: {
accessToken: '',
},
get_access_token() {
const grant_type = 'client_credentials';
const client_id = '你的';
const client_secret = '你的';
var that = this;
wx.request({
url: 'https://aip.baidubce.com/oauth/2.0/token',
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
grant_type: grant_type,
client_id: client_id,
client_secret: client_secret
},
success: function(res) {
if (res.statusCode === 200) {
if (res.data.access_token) {
console.log('Access Token Request Success:', res);
const getToken = res.data.access_token;
that.globalData.accessToken = getToken;
wx.setStorageSync('accessToken', getToken); // 存储到本地
console.log('Access Token:', getToken);
} else {
console.error('Access Token not found in response:', res);
}
} else {
console.error('Access Token Request Failed with status code:', res.statusCode, 'Response:', res);
}
},
fail: function(res) {
console.error('Request Failed:', res);
},
complete: function(res) {
console.log('Request complete');
}
});
},
});
city.json
{
"pages": [
"pages/index/index"
],
"window": {
"navigationBarTitleText": "图片识别",
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black",
"backgroundColor": "#eeeeee",
"backgroundTextStyle": "light"
}
}
city.wxml
<!-- 图片展示 -->
<view class="top-img">
<image src="{{image}}" ></image>
</view>
<!-- 选择图片及图片识别 -->
<view class="center">
<text class="selece-img" wx:if="{{isShow}}">请选择图片!</text>
<button bindtap="imgSelect">选择图片</button>
<button type="primary" bindtap="plant" >图片识别</button>
</view>
<!-- 识别结果 -->
<view class="bottom" wx:if="{{result.length != 0}}">
<view class="title">
<text>图片名称</text>
<text>识别率</text>
</view>
<view class="info" wx:for="{{result}}" wx:key="index">
<text>{{item.name}}</text>
<text>{{item.score}}</text>
</view>
</view>
city.wxss
.top-img{
margin: 20rpx;
width: 95%;
height: 440rpx;
border:1rpx solid #efefef;
border-radius: 20rpx;
box-shadow: 1rpx 1rpx 15rpx #ddd;
overflow: hidden;
}
.top-img image{
width: 100%;
height: 100%;
}
.center{
margin: 20rpx;
width: 95%;
}
.selece-img{
font-size: 26rpx ;
color:red;
}
.center button{
margin-top: 30rpx;
}
.bottom{
margin: 20rpx;
width: 95%;
height: 300rpx;
border:1rpx solid #efefef;
border-radius: 20rpx;
box-shadow: 1rpx 1rpx 15rpx #ddd;
}
.title{
display: flex;
justify-content: space-around;
margin-top: 20rpx;
}
.title text {
font-weight: 700;
font-size: 32rpx;
}
.info{
display: flex;
justify-content: space-around;
margin-top: 20rpx;
}
index.js
// pages/index/index.js
const api = require('../../utils/api');
Page({
data: {
imageSrc: '',
result: '',
accessToken: null,
},
onLoad() {
// 从本地存储中获取 accessToken
let accessToken = wx.getStorageSync('accessToken');
if (accessToken) {
this.setData({ accessToken });
console.log('Loaded Access Token from storage:', accessToken);
} else {
console.log('Access Token not found in storage');
api.get_access_token((token) => {
if (token) {
this.setData({ accessToken: token });
console.log('Access Token Retrieved:', token);
} else {
console.error('Failed to get Access Token');
this.setData({ result: 'Access Token未获取,请重试。' });
}
});
}
},
chooseImage() {
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
const tempFilePath = res.tempFilePaths[0];
this.setData({
imageSrc: tempFilePath,
result: '识别中...', // 显示识别中
});
this.uploadImage(tempFilePath);
},
fail: (err) => {
console.error('选择图片失败', err);
},
});
},
uploadImage(filePath) {
wx.getFileSystemManager().readFile({
filePath: filePath,
encoding: 'base64',
success: (res) => {
this.recognizeImage(res.data);
},
fail: (err) => {
console.error('读取文件失败', err);
},
});
},
recognizeImage(imageBase64) {
const accessToken = this.data.accessToken;
console.log('Using Access Token:', accessToken);
if (!accessToken) {
console.error('Access Token未获取');
this.setData({
result: 'Access Token未获取,请重试。',
});
return;
}
wx.request({
url: `https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=${accessToken}`,
method: 'POST',
data: {
image: imageBase64,
},
header: {
'content-Type': 'application/x-www-form-urlencoded',
},
success: (res) => {
if (res.data.result) {
const results = res.data.result.map(item => `名称: ${item.keyword}, 置信度: ${item.score}`).join('\n');
this.setData({
result: results,
});
} else {
console.error('识别失败', res);
this.setData({
result: '识别失败,请重试。',
});
}
},
fail: (err) => {
console.error('请求失败', err);
this.setData({
result: '请求失败,请检查网络连接。',
});
},
});
},
});
index.json
{
"usingComponents": {
}
}
index.wxml
<!-- pages/index/index.wxml -->
<view class="container">
<button bindtap="chooseImage">选择图片</button>
<image src="{{imageSrc}}" mode="widthFix" style="width: 100%; margin-top: 20px;"></image>
<view style="margin-top: 20px;">
<text selectable="true" style="white-space: pre-wrap;">{{result}}</text>
</view>
</view>
index.wxss
/* pages/index/index.wxss */
.container {
padding: 20px;
}
button {
display: block;
margin: 0 auto;
}
app.js
// app.js
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
},
globalData: {
userInfo: null
}
})
app.json
{
"pages": [
"pages/index/index",
"pages/city/city",
"pages/logs/logs"
],
"window": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "Weixin",
"navigationBarBackgroundColor": "#ffffff"
},
"style": "v2",
"componentFramework": "glass-easel",
"sitemapLocation": "sitemap.json",
"lazyCodeLoading": "requiredComponents"
}
app.wxss
/**app.wxss**/
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 200rpx 0;
box-sizing: border-box;
}
结果展示: