上一篇介绍了环境的搭建,这一篇介绍开发细节。主要包括两方面,
-
调用Google Cloud Vision API 分析图片
-
微信小程序图片上传。
分析图片(通过Vision API实现)
之前已经配置好了调用API的环境,现在就来编写代码调用API。
from google.cloud import vision
def call_vision_api(f):
vision_client = vision.Client()
image = vision_client.image(content=f.read())
labels = image.detect_labels()
label_list = [label.description for label in labels]
return label_list
def detet_image(file_name):
with open(file_name, 'rb') as f:
return call_vision_api(f)
if __name__ == '__main__':
print(detet_image('test.jpg'))
详细说明见Google Cloud Vision API文档和Python Using the Vision API
微信小程序图片上传
这里分为两部分:
-
django服务端接收图片接口。
-
微信小程序上传图片;
首先我先从服务端的接收接口开始介绍。
1)服务端上传接口
现在我们的建立的django项目的目录结构
wxbackground/
├── db.sqlite3
├── manage.py
└── wxbackground
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
-
首先在wxbackground/wxbackground/目录下建立views.py。因为微信小程序上传是是发送的POST情况,所以我们的view.py里面也应该接收POST请求。view.py中代码如下。
from django.http import HttpResponse
def upload(request):
if request.method == 'POST':
return HttpResponse('This is POST!')
else:
return HttpResponse('Hello world!')
同时需要修改同一目录下的urls.py文件,这个是django的路由,通过在这个文件中配置才能正确的访问到目标函数。urls.py代码如下:
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test/', views.upload),
]
配置完成后在manage.py路径下输入
$:python3 manage.py runserver 0.0.0.0:8000
在浏览器中输入云虚拟机ip:8000/upload/测试是否配置完成,若配置ok则浏览器页面会显式“Hello world!”。
-
在views.py编写接收文件代码,并调用之前写的图片分析函数。首先将刚才编写的detect_labels.py放入当前目录下。
由于我们并不想保存上传的图片,所以我们直接将上传图片流再上传到谷歌API中检测。
view.py中代码如下:
from django.http import HttpResponse
from . import detect_labels
def upload(request):
if request.method == 'POST':
img = request.FILES.get('picture')
if img is None:
return HttpResponse('You need upload a picture!')
labels = detect_labels.call_vision_api(img)
return HttpResponse(str(labels))
else:
return HttpResponse('Hello world!')
这里说明一下,在django中,从FILES.get('picture')
得到的文件类型为InMemoryUploadedFile
类型,通过调用其read()
函数,获得图片IO
流。而Vision API需要的也是IO
流,所以程序中直接将InMemoryUploadedFile
作为call_vision_api
函数的输入不会发生类型错误。
2)微信小程序上传
在配置上传之前,需要先在微信公众平台官网中,将域名添加到添加uploadFile合法域名。可以参看微信小程序 wx.request合法域名配置详解。
微信小程序上传需要两个步骤:
-
选择图片;
-
上传图片。
在微信小程序API中wx.uploadFile(OBJECT)这里其实已经介绍得很清楚了。
我的上传代码index.js如下:
const uploadFileUrl = 'https://yoursite/upload/'
Page({
data: {
imageSrc: null,
},
chooseImage: function () {
var that = this
wx.chooseImage({
sourceType: ['camera', 'album'],
sizeType: ['compressed'],
count: 1,
success: function (res) {
console.log(res)
that.setData({
imageSrc: res.tempFilePaths[0]
})
}
})
},
check: function (e) {
var that = this
wx.uploadFile({
url: uploadFileUrl,
name: 'picture',
filePath: that.data.imageSrc,
formData: {
'user': 'test'
},
success: function (res) {
console.log('imageSrc is:', that.data.imageSrc)
console.log('uploadImage success, res is:', res)
wx.showModal({
title: "图片详情",
content: res.data,
showCancel: false,
confirmText: "确定"
})
},
fail: function ({errMsg}) {
console.log('uploadImage fail, errMsg is', errMsg)
}
})
},
reload: function (e) {
this.setData({
imageSrc: null
})
}
})
微信小程序界面布局index.wxml如下:
<view class="container">
<view class="page-body">
<view class="page-section">
<view class="page-body-info">
<block wx:if="{{imageSrc}}">
<view class="weui-uploader__files">
<view class="weui-uploader__file">
<image class="weui-uploader__img" src="{{imageSrc}}"></image>
</view>
</view>
</block>
<block wx:else>
<view class="image-plus image-plus-nb" bindtap="chooseImage">
<view class="image-plus-horizontal"></view>
<view class="image-plus-vertical"></view>
</view>
<view class="image-plus-text">选择图片</view>
</block>
</view>
<view class="body-view">
<button type="default" bindtap="check">检测</button>
</view>
<view class="body-view">
<button type="default" bindtap="reload">重置</button>
</view>
</view>
</view>
</view>
这里有个小坑,注意一下:微信小程序在电脑上开发时,wx.chooseImage
中的sizeType: ['compressed']
不会生效,只有在微信上调用小程序时才会生效。
完结
现在服务端与微信小程序已经搭建完毕,现在我们就可以测试是否能够上传成功。完结撒花。