pom.xml依赖:
<dependencies><dependency><groupId>com.baidu.aip</groupId><artifactId>java-sdk</artifactId><version>4.16.11</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.48</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.4</version></dependency></dependencies>
sss: (这个使用来获取token的)
package Jframe;import org.json.JSONObject;import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Map;public class ssss {public static String getAuth() {// 官网获取的 API Key 更新为你注册的String clientId = "*******";// 官网获取的 Secret Key 更新为你注册的String clientSecret = "***********";return getAuth(clientId, clientSecret);}/*** 获取API访问token* 该token有一定的有效期,需要自行管理,当失效时需重新获取.* @param ak - 百度云官网获取的 API Key* @param sk - 百度云官网获取的 Secret Key* @return assess_token 示例:* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"*/public static String getAuth(String ak, String sk) {// 获取token地址String authHost = "https://aip.baidubce.com/oauth/2.0/token?";String getAccessTokenUrl = authHost// 1. grant_type为固定参数+ "grant_type=client_credentials"// 2. 官网获取的 API Key+ "&client_id=" + ak// 3. 官网获取的 Secret Key+ "&client_secret=" + sk;try {URL realUrl = new URL(getAccessTokenUrl);// 打开和URL之间的连接HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();connection.setRequestMethod("GET");connection.connect();// 获取所有响应头字段Map<String, List<String>> map = connection.getHeaderFields();// 遍历所有的响应头字段for (String key : map.keySet()) {System.err.println(key + "--->" + map.get(key));}// 定义 BufferedReader输入流来读取URL的响应BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String result = "";String line;while ((line = in.readLine()) != null) {result += line;}/*** 返回结果示例*/System.err.println("result:" + result);JSONObject jsonObject = new JSONObject(result);String access_token = jsonObject.getString("access_token");return access_token;} catch (Exception e) {System.err.printf("获取token失败!");e.printStackTrace(System.err);}return null;}public static void main(String[] args) {getAuth();} }
interpt:(调用接口)
package Jframe;import bean.Animal; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.baidu.aip.imageclassify.AipImageClassify; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONObject;import java.io.BufferedReader; import java.util.HashMap; import java.util.List;public class interpt {public static String Animal(AipImageClassify client,String path) {// 传入可选参数调用接口HashMap<String, String> options = new HashMap<String, String>();options.put("top_num", "1");// 参数为本地路径JSONObject res = client.animalDetect(path, options);/*** JSON转成字串符*/String result1 = res.get("result").toString();JSONArray arr = JSON.parseArray(result1);String jsonObject1 = arr.get(0).toString();com.alibaba.fastjson.JSONObject obj = JSON.parseObject(jsonObject1);String name = obj.getString("name");if (name.equals("非动物")){if (sample(client,path).equals("非植物")){return "非动物,非植物";}elsereturn sample(client,path);}return name; // System.out.println(res.toString(2)); }public static String sample(AipImageClassify client,String path) {// 传入可选参数调用接口HashMap<String, String> options = new HashMap<String, String>();options.put("baike_num", "1");// 参数为本地路径JSONObject res = client.plantDetect(path, options);String result2 = res.get("result").toString();JSONArray arr = JSON.parseArray(result2);String jsonObject1 = arr.get(0).toString();com.alibaba.fastjson.JSONObject obj = JSON.parseObject(jsonObject1);String name = obj.getString("name");return name; // System.out.println(res.toString(2)); } }
main:(页面的实现)
package Jframe;import com.baidu.aip.imageclassify.AipImageClassify;import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File;public class main {public static final String APP_ID = "******";public static final String API_KEY = "*********";public static final String SECRET_KEY = "************";public static String file1;public static void main(String[] args) {AipImageClassify aipImageClassify=new AipImageClassify(APP_ID,API_KEY,SECRET_KEY);JFrame jFrame=new JFrame("图片识别系统");jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);jFrame.setLayout(null);//初始化界面jFrame.setSize(2560,1440); // jFrame.setLocation(320,240);JFileChooser jFileChooser=new JFileChooser();jFileChooser.setFileFilter(new FileFilter() {@Overridepublic boolean accept(File f) {return true;}@Overridepublic String getDescription() {return null;}});// 创建登录按钮JButton SCButton = new JButton("上传图片");JLabel label3 =new JLabel("");label3.setBounds(300,100,200,50);SCButton.setBounds(50, 225, 100, 50);JLabel jLabel = new JLabel();ImageIcon i = new ImageIcon("");//设置ImageIcon jLabel.setIcon(i);//label的大小设置为ImageIcon,否则显示不完整JButton WLButton=new JButton("上传网络验证");WLButton.setBounds(SCButton.getX()+200,SCButton.getY(),150,50);SCButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) { // JOptionPane.showConfirmDialog(null, "上传图片");int returnVal = jFileChooser.showOpenDialog(jFrame);File file=jFileChooser.getSelectedFile();if (returnVal==JFileChooser.APPROVE_OPTION){JOptionPane.showMessageDialog(jFrame, "计划打开文件:" + file.getAbsolutePath());file1=file.getAbsolutePath();file1.replaceAll("\\\\", "/");ImageIcon imageIcon=new ImageIcon(file1);Image image=imageIcon.getImage();//获取此图标的Imageimage=image.getScaledInstance(350,200,Image.SCALE_AREA_AVERAGING);//将image压缩imageIcon.setImage(image);//将压缩以后的照片在传回去 jLabel.setIcon(imageIcon);jLabel.setBounds(25,25,imageIcon.getIconWidth(),imageIcon.getIconHeight());SCButton.setBounds(50, 50+imageIcon.getIconHeight(), 100, 50);WLButton.setBounds(175, 50+imageIcon.getIconHeight(), 100, 50);label3.setBounds(50+imageIcon.getIconWidth(),100,800,100);}}});WLButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) { // JOptionPane.showConfirmDialog(null, "上传网络验证");String name=interpt.Animal(aipImageClassify,file1); // System.out.println(name);label3.setText("经过网络查询这个是:"+name);label3.setFont(new Font(Font.DIALOG,1,25));}});jFrame.add(WLButton);jFrame.add(SCButton);jFrame.add(jLabel);jFrame.add(label3);jFrame.setVisible(true);}}