1.通过网址识别在线图片
前端代码:
点击检测按钮,调用相应的方法,然后简单的发起个axios网络请求
axios({
url: 'http://localhost:8080/distinguish/url?params='+网络图片网址,
methods: "post",
}).then(function (response) {
console.log(response);
/* 返回成功后将结果渲染在页面 */
},function(err){
console.log(err);
})
后端代码:
百度识图提供的源码模板,我们要做的就是将前端传来的值拼接,然后调用api
@RequestMapping("distinguish")
@RestController
@CrossOrigin
public class UserController {
@RequestMapping(value = "url")
public String test1(String params){
String path = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";
ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
System.out.println("params"+params);
// 设置header参数
request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
// 设置query参数
request.addQueryParameter("access_token", "自己的access_token");
// 设置jsonBody参数
// 百度识图提供的源码模板,我们要做的就是将前端传来的值拼接,然后调用api
String jsonBody = "url="+params;
request.setJsonBody(jsonBody);
ApiExplorerClient client = new ApiExplorerClient();
try {
ApiExplorerResponse response = client.sendRequest(request);
// 返回结果格式为Json字符串
System.out.println(response.getResult());
return response.getResult();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
后端返回结果:
2.通过本地上传文件识图
前端代码:
页面按钮:
<div>
<!-- 按钮标签遮盖input自带的本地上传文件的样式,并调起文件类型的input的事件 -->
<button onclick="upload.click()" class="SecondBtn" style="color: white;">
本地上传
</button>
<!-- 这里的ref在vue中当标签id用,调用loadUrl方法,只接受图片类型的文件 -->
<input ref="inputFile" @change="loadUrl()" accept="image/png,image/gif,image/jpeg"
type="file" name="upload" id="upload" method="post" enctype="multipart/form-data"
style="display: none;" />
</div>
vue代码:
loadUrl(){
let myHeaders = new Headers();
//用User-Agent来发送头请求
myHeaders.append("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)");
let formdata = new FormData();
//console.log输出formdata,游览器控制台输出为空,正常现象
formdata.append("file", this.$refs.inputFile.files[0]);
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("http://localhost:8080/distinguish/urlPath", requestOptions)
.then(response => response.json())
.then(test => {
console.log('result',test.result[0].name)
/* 将返回结果渲染页面 */
})
.catch(error => {
console.log('error', error)
});
将图片背景变为用户上传的图片
let uurl = new Image()
if (window.createObjectURL != undefined) { // basic
uurl.src = window.createObjectURL(this.$refs.inputFile.files[0])
} else if (window.URL != undefined) { // mozilla(firefox)
uurl.src = window.URL.createObjectURL(this.$refs.inputFile.files[0])
} else if (window.webkitURL != undefined) { // webkit or chrome
uurl.src =
window.webkitURL.createObjectURL(this.$refs.inputFile.files[0])
}
console.log('uurl',uurl.src)
// Url为图片背景
// <div :style="{backgroundImage: 'url(' + Url+ ')'}"></div>
this.Url=uurl.src
},
后端配置以及相关代码:
application.properties中的配置
spring.servlet.multipart.max-file-size=3MB
#这条路径是自己自定义的,用来存放上传后加工的图片文件
file.upload.path=D:/Program Files (x86)/Project/BackendPart/testImg/
@RequestMapping("distinguish")
@RestController
@CrossOrigin
public class UserController {
@Value("${file.upload.path}")
private String path;
//创建日期函数,用来区分图片上传日期
Date currentTime = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd HHmm");
String dateString = format.format(currentTime);
@RequestMapping(value = "urlPath",method = RequestMethod.POST)
@ResponseBody
//用MultipartFile 类型来接收文件
public String test2(@RequestPart MultipartFile file) throws IOException{
//获取文件路径
String fileName = file.getOriginalFilename();
//避免文件名相同,在文件后拼接个随机数
int random_number = (int)(Math.random() * (1000 - 1 + 1) + 1);
String filePath = path + dateString + random_number + fileName ;
//插件文件对象,将路径存放,没有文件就创建文件
File dest = new File(filePath);
//将源文件copy到目标文件file.getInputStream()->dest.toPath(),将上传的文件写到指定目录
Files.copy(file.getInputStream(),dest.toPath());
//以下为百度识图官方提供的代码模板
String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant";
System.out.println("filePath:"+dest.getAbsolutePath());
try{
String imgUrl = dest.getAbsolutePath();
//转码
//FileUtil、Base64Util、URLEncoder等工具类下载
//https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
//https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
//https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
//https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
byte[] imgData = FileUtil.readFileByBytes(imgUrl);
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr,"UTF-8");
String param = "image=" + imgParam;
String accessToken="自己的access_token";
// 设置jsonBody参数
String result = HttpUtil.post(url, accessToken, param);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
到此,一个识图的小项目就这样完成了