`

java调用平台提供的接口进行图片识别

    博客分类:
  • java
阅读更多
图片识别平台:https://www.juhe.cn/
调用平台提供的接口进行图片识别

注:将本地图片进行Base64位编码
本类只用到这两个方法:encodeImgageToBase64(),readContentFromPost()。


代码:

package com.teamdev.jxbrowser.chromium.demoJD.yyzz;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.imageio.ImageIO;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.teamdev.jxbrowser.chromium.demoJD.yyzz.ImageUtils;

import sun.misc.BASE64Encoder;

public class ImageUtils {
/**
     * 将本地图片进行Base64位编码
     * 
     * @param imgUrl
     *        图片的url路径,如xxx.jpg
     * @return
     */ 
    @SuppressWarnings("deprecation")
public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 
        ByteArrayOutputStream outputStream = null; 
        try { 
            BufferedImage bufferedImage = ImageIO.read(imageFile); 
            outputStream = new ByteArrayOutputStream(); 
            ImageIO.write(bufferedImage, "jpg", outputStream); 
        } catch (MalformedURLException e1) { 
            e1.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        // 对字节数组Base64编码 
        BASE64Encoder encoder = new BASE64Encoder(); 
        return java.net.URLEncoder.encode( encoder.encode(outputStream.toByteArray()));// 返回Base64编码过的字节数组字符串 
    } 
    /**
* 删除会话文件
* */
public static void DeleteSession() {
String path="F:\\yzm\\yzm.jpg";
File file =new File(path);
if (file.exists()) {
try {
file.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("faile delete session.txt ");
}
}  
}
/**
* 下载图片
* */
public static void runDownLoad(String fileurl) {
// 构造URL
URL url;
try {
url = new URL(fileurl);
// 打开URL连接
URLConnection con = (URLConnection) url.openConnection();
// 得到URL的输入流
InputStream input = con.getInputStream();
// 设置数据缓冲
byte[] bs = new byte[1024 * 2];
// 读取到的数据长度
int len;
// 输出的文件流保存图片至本地
String path1 = "F:\\yzm\\yzm.jpg";
File f = new File(path1);
// f.mkdirs();
OutputStream os = new FileOutputStream(path1);
while ((len = input.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.close();
input.close();
} catch (MalformedURLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}

/**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
/**
* 解析验证码
* @throws Exception
* */

public static String  readContentFromPost(String imgPath) throws IOException {
String str = ImageUtils.encodeImgageToBase64(new File(imgPath));
URL postUrl = new URL("http://op.juhe.cn/vercode/index");
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
String content = "codeType=8003&&image=&base64Str=" + str + "&dtype=&key=bdb9286128139fa1a61d8b7ca84ab171";
out.writeBytes(content);

out.flush();
out.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
         StringBuilder sb=new StringBuilder();
while ((line = reader.readLine()) != null) {
System.out.println(line);
sb.append(line);
}
//{"reason":"成功的返回","result":"rahu","error_code":0}
String result=sb.toString().split("result\":\"")[1].split("\",")[0];
reader.close();
connection.disconnect();
return result;
}
   

//测试
    public static void main(String[] args) throws IOException{
    System.out.println(readContentFromPost("F:\\yzm\\yzm.jpg"));
    }
 
}












==================================================================自己的代码
package com.teamdev.jxbrowser.chromium.demoJD.yyzz;
/**
* 抓取京东营业执照信息
* */

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserPreferences;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.LoggerProvider;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

public class jd_yyzz {
private static final Color White = null;

/**
*======== 主方法
* */
public static void main(String[] args) throws Exception {
//获取url,解析验证码
String shop_url =Get_Shop_url();
String html=saveImage(shop_url);
System.out.println(html);
}
/**
* ========获取url
* */
public static String Get_Shop_url(){
//此处连接数据库,查询出所有url
String shop_url="https://mall.jd.com/showLicence-652046.html";
return shop_url;
}
/**
* 模拟器截图(只是截取验证码), 调用接口,解析验证码,填入输入框并点击验证,返回验证成功后的html数据
* */
public static String saveImage(String url){
LoggerProvider.getBrowserLogger().setLevel(Level.SEVERE);
LoggerProvider.getIPCLogger().setLevel(Level.SEVERE);
LoggerProvider.getChromiumProcessLogger().setLevel(Level.SEVERE);

Browser browser = new Browser();

BrowserView view = new BrowserView(browser);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(700, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
BrowserPreferences preferences = browser.getPreferences();
preferences.setImagesEnabled(false);

int viewWidth = 1280;
int viewHeight = 1000;
// Resize view to the required size
view.setBounds(new Rectangle(viewWidth, viewHeight));
// Wait until web page is loaded completely
invokeAndWaitReady(browser,new jd_yyzz().new ViewThread(browser, url));

JSValue bodyHeight = null;
int firstHeight = 400;
int nowHeight = 400;

while (firstHeight != nowHeight) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
firstHeight = nowHeight;

bodyHeight = browser.executeJavaScriptAndReturnValue("document.body.scrollHeight");
//nowHeight = 900;
for (int i = firstHeight; i < nowHeight; i = i + 300) {
browser.executeJavaScriptAndReturnValue("window.scrollTo(0,"+ i + ")");
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
System.out.println(firstHeight + ":" + nowHeight);
}
viewHeight = nowHeight + 50;
view.setBounds(new Rectangle(viewWidth, viewHeight));
System.out.println("11111------------------:" + viewHeight);
try {
Thread.sleep(1000 * 1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
bodyHeight = browser.executeJavaScriptAndReturnValue("document.body.scrollHeight");
System.out.println("222222------------------:" + bodyHeight);
int viewHeight_new = ((Number) bodyHeight.getNumber()).intValue() + 50;
if (viewHeight_new > viewHeight) {
System.out.println("33333------------------:" + viewHeight_new);
}
Image image = view.getImage();
BufferedImage bufferedImage = new BufferedImage(100, 50,BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics();
Double scale = 1.0 / view.getDeviceScaleFactor();
graphics.scale(scale, scale);
graphics.drawImage(image,-585, -355, image.getWidth(view), image.getHeight(view),White, null);
try {
String path = "f://shopdetails.jpg";
ImageIO.write(bufferedImage, "JPG", new File(path));
bufferedImage = null;
} catch (IOException e) {
e.printStackTrace();
}

//验证码图片保存之后获取验证码
try {
String result=ImageUtils.readContentFromPost("f://shopdetails.jpg");
browser.executeJavaScriptAndReturnValue("document.getElementById('verifyCode').value = \""+ result + "\";");
Thread.sleep(1000 * 1);
browser.executeJavaScriptAndReturnValue("document.getElementsByClassName('btn')[0].click();");
Thread.sleep(1000 * 1);
return browser.getHTML();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/**
* 线程
* */
class ViewThread extends Thread {
Browser browser;
String openUrl;

public ViewThread(Browser browser, String openUrl) {
this.browser = browser;
this.openUrl = openUrl;
}

public void run() {

browser.loadURL(openUrl);

}
}

/**
* 模拟器加载url
* */
public static void invokeAndWaitReady(Browser browser, Runnable runnable) {
final CountDownLatch latch = new CountDownLatch(1);
LoadAdapter listener = new LoadAdapter() {
@Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
latch.countDown();
}
}
};
browser.addLoadListener(listener);
try {
runnable.run();
try {
if (!latch.await(60, TimeUnit.SECONDS)) {
// throw new RuntimeException(new TimeoutException());
}
} catch (InterruptedException ignore) {
ignore.printStackTrace();
Thread.currentThread().interrupt();
}
} finally {
browser.removeLoadListener(listener);
}
}
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics