百度的人工智能接口,可以实现诸如人脸识别,文字识别等等。当今比较火的springboot,加上人工智能模块,未来应该应用蛮广泛的。因此,闲来无事写了个小栗子,分享出来!终极效果如下~
没错,是用的bootstrapFileupload,这个挺赞的小组件~和bootstrap很兼容,样式也很漂亮!
废话少说,直接上码!
咱是基于maven构建的程序,so需要引入百度的依赖,还有处理对象和json的依赖jackson,当然你有别的方法也可。如下:(PS:如果你用的jar包,就需要搜索这些jar了,不多说,复制groupId就会搜到,这里不再提到,需要注意的是,这里所使用的百度依赖,需要jdk1.8及以上版本)
<!-- 百度人工智能依赖 -->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.4.1</version>
</dependency>
<!-- 对象转换成json引入如下依赖 -->
<!-- 文档:https://www.yiibai.com/jackson/jackson_first_application.html#article-start -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
然后,咱页面是这样子滴:
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta contentType="application/x-www-form-urlencoded">
<script src="plugin/js/jquery-3.1.1.min.js" type="text/javascript"></script>
<!-- bootstrap main js -->
<script type="text/javascript" src="plugin/js/bootstrap.min.js"></script>
<!-- fileinput main js -->
<script type="text/javascript" src="plugin/js/fileinput.min.js"></script>
<!-- chn language js -->
<script type="text/javascript" src="plugin/js/zh.js"></script>
<!-- bootstrap theme -->
<link rel="stylesheet" type="text/css" href="plugin/css/bootstrap.min.css">
<!-- fileinput theme -->
<link rel="stylesheet" type="text/css" href="plugin/css/fileinput.min.css">
<title>文件上传</title>
</head>
<body>
<h1>文字识别<!--<p th:text="'我是文本输出'"></p>--></h1>
<form enctype="multipart/form-data" id="ocr-form" action="/ocr" method="post">
<div class="col-sm-4">
<div class="form-group">
<input type="file" name="file" id="file1" class="file">
</div>
</div>
<div class="col-sm-4">
<h2>解析结果:</h2>
<span id="res"></span>
</div>
</form>
<script>
$("#file1").fileinput({
uploadUrl: '/ocr', //你必须在这里设置一个有效的URL,否则你会得到一个错误
uploadAsync: true, //AJAX设置同步,异步的上传方式 (同步)
allowedFileExtensions: ['jpg', 'png', 'gif'],//文件类型
showUpload: true, //是否显示上传按钮
//browseClass: "btn btn-primary", //按钮样式
showRemove : true, //显示移除按钮
dropZoneEnabled: true,//是否显示拖拽区域
overwriteInitial: false,
//maxFileSize:0,//单位为kb,如果为0表示不限制文件大小
maxFilesNum: 10,
maxFileCount: 4, //表示允许同时上传的最大文件个数
minFileCount: 0, //最少文件
validateInitialCount:false//异步上传返回结果处理
}).on('fileuploaded', function(event, data, previewId, index) {
// alert(JSON.stringify(data));
var res_arr = data.response.words_result;
for(var key in res_arr){
console.log(res_arr[key].words);
$('#res').append(res_arr[key].words + "<br/>");
}
// console.log(JSON.stringify(data));
});
</script>
</body>
</html>
上面的HTML好像没啥特别的,注意咱引入的文件,不缺就没问题~其次就是fileupload的初始化配置了,注释很全不解释~
然后,就是controller里接住它提交的图片咯,具体代码如下:
package com.lvfeng.system.ai;
import com.baidu.aip.ocr.AipOcr;
import com.lvfeng.tool.baidu.AIP;
import com.lvfeng.tool.change.JSONChange;
import com.lvfeng.tool.chars.encrypt.EncryptUtil;
import org.json.JSONObject;
import org.springframework.stereotype.Controller; //貌似只能用RestController,这个Controller好像不好使
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;
/**
* 文字识别OCR模块控制器
*/
@RestController
public class OCRController {
@RequestMapping(value = "/ocr",method = RequestMethod.POST)
public Map ocr(MultipartFile file) throws Exception{
//接收图像二进制数据
byte[] buf = file.getBytes();
//参数解密
String key = "love10240wsw";
EncryptUtil des = new EncryptUtil(key, "utf-8");
//初始化百度接口
AipOcr client = new AipOcr(des.deCode(AIP.APP_ID_TEXT),des.deCode(AIP.API_KEY_TEXT),des.deCode(AIP.SECRET_KEY_TEXT));
//首选参数
HashMap<String, String> options = new HashMap<String, String>();
options.put("language_type", "CHN_ENG"); //中英语言
JSONObject res = client.basicGeneral(buf, options);
Map map = JSONChange.json2map(res.toString());
System.out.println(res.toString());
return map;
}
}
鼓捣了半天,发现,还是扔出去map,fileupload才认识他,原来,map在springboot返回的时候会自动转换成json,json天生的“好人缘”,被fileupload逮住从而操作dom显示出来。上面代码中,加密的DES部分可以忽略,直接在new AipOcr(appID,appKey,secretKey)传入就行。这三个参数在你注册百度开发者平台并创建文字识别程序的时候就有了。怎么创建程序?查看咱以前文章,百度人工智能程序创建,或者百度~
还有json转换成map的代码顺便贴出来吧~如下:
/**
* 005.json字符串转换为map
*/
public static <T> Map<String, Object> json2map(String jsonString) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper.readValue(jsonString, Map.class);
}
百度的其他功能也可以这么玩,关于这个接口的调用将持续更新~