图形验证码识别接口(免费)

温馨提示:
本文最后更新于 2022年07月04日,已超过 925 天没有更新。若文章内的图片或资源失效,请留言反馈或直接联系我

一、效果演示:http://www.bhshare.cn/imgcode/demo.html

  1. 本地图片识别
    本地上传识别.png
  2. 网络图片识别
    网络图片识别.png

二、免费api接口

接口地址:http://www.bhshare.cn/imgcode/

请求类型:post

接口参数:

参数名 类型 是否必需 备注
token String 用户标识(token 免费获取:http://www.bhshare.cn/imgcode/gettoken
type String 识别类型。”online“:网络图片识别,”local“:本地图片上传
uri String 在线图片网址或图片base64编码(含头部信息),当type取online时生效
file file 本地图片文件,当type取local时生效

返回数据:

数据格式:json

参数名 类型 备注
code int 状态码,200:识别成功,其他:识别失败
msg String 错误提示信息,当code!=200时有意义
data String 识别结果
  1. python实现
# -*- coding: utf-8 -*-
# @Date : 2021/10/03
# @Author : 薄荷你玩
# @Website :http://www.bhshare.cn

import json
import requests

TOKEN = 'free'  # token 获取:http://www.bhshare.cn/imgcode/gettoken
URL = 'http://www.bhshare.cn/imgcode/'  # 接口地址


def imgcode_online(imgurl):
    """ 在线图片识别 :param imgurl: 在线图片网址 / 图片base64编码(包含头部信息) :return: 识别结果 """
    data = {
   
        'token': TOKEN,
        'type': 'online',
        'uri': imgurl
    }
    response = requests.post(URL, data=data)
    print(response.text)
    result = json.loads(response.text)
    if result['code'] == 200:
        print(result['data'])
        return result['data']
    else:
        print(result['msg'])
        return 'error'


def imgcode_local(imgpath):
    """ 本地图片识别 :param imgpath: 本地图片路径 :return: 识别结果 """
    data = {
   
        'token': TOKEN,
        'type': 'local'
    }

    # binary上传文件
    files = {
   'file': open(imgpath, 'rb')}

    response = requests.post(URL, files=files, data=data)
    print(response.text)
    result = json.loads(response.text)
    if result['code'] == 200:
        print(result['data'])
        return result['data']
    else:
        print(result['msg'])
        return 'error'


if __name__ == '__main__':
    imgcode_online('http://www.bhshare.cn/test.png')

    imgcode_local('img/test.png')

    # 输出样例:
    # {'code': 200, 'msg': 'ok', 'data': '74689'}
    # 74689
    
  1. Java实现
 /** * @author 薄荷你玩 * @date 2021/10/04 * @Website http://www.bhshare.cn */
 
 import java.io.BufferedReader;
 import java.io.DataOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.net.URLEncoder;
 import java.nio.charset.StandardCharsets;
 import java.util.*;
 import java.util.Map.Entry;
 import javax.imageio.ImageIO;
 import javax.imageio.stream.ImageInputStream;
 
 
 public class ImgcodeUtil {
   
 
     private static final String URL = "http://www.bhshare.cn/imgcode/"; //接口地址
     private static final String TOKEN = "free"; // token 获取:http://www.bhshare.cn/imgcode/gettoken
 
     private final static String BOUNDARY = UUID.randomUUID().toString().toLowerCase().replaceAll("-", "");// 边界标识
     private final static String PREFIX = "--";// 必须存在
     private final static String LINE_END = "\r\n";
 
 
     /** * 网络图片识别 * * @param imgUrl 图片网址/图片base64编码 * @return 服务器返回结果(json格式) */
     private static String imgcode_online(String imgUrl) {
   
         String BOUNDARY = UUID.randomUUID().toString(); // 文件边界随机生成
         HttpURLConnection con = null;
         BufferedReader buffer = null;
         StringBuffer resultBuffer = null;
         try {
   
             URL url = new URL(URL);
             //得到连接对象
             con = (HttpURLConnection) url.openConnection();
             //设置请求类型
             con.setRequestMethod("POST");
             //设置请求需要返回的数据类型和字符集类型
             con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 
             //允许写出
             con.setDoOutput(true);
             //允许读入
             con.setDoInput(true);
             //不使用缓存
             con.setUseCaches(false);
             DataOutputStream out = new DataOutputStream(con.getOutputStream());
             String content = "token=" + TOKEN;
             content += "&type=online";
             content += "&uri=" + URLEncoder.encode(imgUrl);
             // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
             out.writeBytes(content);
             out.flush();
             out.close();
             //得到响应码
             int responseCode = con.getResponseCode();
             if (responseCode == HttpURLConnection.HTTP_OK) {
   
                 //得到响应流
                 InputStream inputStream = con.getInputStream();
                 //将响应流转换成字符串
                 resultBuffer = new StringBuffer();
                 String line;
                 buffer = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                 while ((line = buffer.readLine()) != null) {
   
                     resultBuffer.append(line);
                 }
                 return resultBuffer.toString();
             }
 
         } catch (Exception e) {
   
             e.printStackTrace();
         }
         return "";
     }
 
     /** * 本地图片上传 * * @param path 图片路径 * @return 返回数据(json) */
     public static String imgcode_local(String path) throws Exception {
   
         HttpURLConnection conn = null;
         InputStream input = null;
         OutputStream os = null;
         BufferedReader br = null;
         StringBuffer buffer = null;
         try {
   
             URL url = new URL(URL);
             conn = (HttpURLConnection) url.openConnection();
 
             conn.setDoOutput(true);
             conn.setDoInput(true);
             conn.setUseCaches(false);
             conn.setConnectTimeout(1000 * 10);
             conn.setReadTimeout(1000 * 10);
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
 
             conn.connect();
 
             // 往服务器端写内容 也就是发起http请求需要带的参数
             os = new DataOutputStream(conn.getOutputStream());
             // 请求参数部分
             Map requestText = new HashMap();
             requestText.put("token", TOKEN);
             requestText.put("type", "local");
             writeParams(requestText, os);
             // 请求上传文件部分
             writeFile(path, os);
             // 请求结束标志
             String endTarget = PREFIX + BOUNDARY + PREFIX + LINE_END;
             os.write(endTarget.getBytes());
             os.flush();
 
             // 读取服务器端返回的内容
             if (conn.getResponseCode() == 200) {
   
                 input = conn.getInputStream();
             } else {
   
                 input = conn.getErrorStream();
             }
             br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
             buffer = new StringBuffer();
             String line = null;
             while ((line = br.readLine()) != null) {
   
                 buffer.append(line);
             }
         } catch (Exception e) {
   
             throw new Exception(e);
         } finally {
   
             try {
   
                 if (conn != null) {
   
                     conn.disconnect();
                     conn = null;
                 }
                 if (os != null) {
   
                     os.close();
                     os = null;
                 }
                 if (br != null) {
   
                     br.close();
                     br = null;
                 }
             } catch (IOException ex) {
   
                 throw new Exception(ex);
             }
         }
         return buffer.toString();
     }
 
     /** * 对post参数进行编码处理并写入数据流中 * * @throws Exception * @throws IOException */
     private static void writeParams(Map requestText, OutputStream os) throws Exception {
   
         try {
   
 
             StringBuilder requestParams = new StringBuilder();
             Set set = requestText.entrySet();
             Iterator it = set.iterator();
             while (it.hasNext()) {
   
                 Entry entry = (Entry) it.next();
                 requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
                 requestParams.append("Content-Disposition: form-data; name=\"")
                         .append(entry.getKey()).append("\"").append(LINE_END);
                 requestParams.append("Content-Type: text/plain; charset=utf-8")
                         .append(LINE_END);
                 requestParams.append("Content-Transfer-Encoding: 8bit").append(
                         LINE_END);
                 requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
                 requestParams.append(entry.getValue());
                 requestParams.append(LINE_END);
             }
             os.write(requestParams.toString().getBytes());
             os.flush();
         } catch (Exception e) {
   
             throw new Exception(e);
         }
     }
 
     /** * 对post上传的文件进行编码处理并写入数据流中 * * @throws IOException * @path 文件路径 */
     private static void writeFile(String path, OutputStream os) throws Exception {
   
         try {
   
             InputStream is = null;
             File file = new File(path);
             StringBuilder requestParams = new StringBuilder();
             requestParams.append(PREFIX).append(BOUNDARY).append(LINE_END);
             requestParams.append("Content-Disposition: form-data; name=\"")
                     .append("file").append("\"; filename=\"")
                     .append(file.getName()).append("\"")
                     .append(LINE_END);
             requestParams.append("Content-Type:")
                     .append(getContentType(file))
                     .append(LINE_END);
             requestParams.append("Content-Transfer-Encoding: 8bit").append(
                     LINE_END);
             requestParams.append(LINE_END);// 参数头设置完以后需要两个换行,然后才是参数内容
 
             os.write(requestParams.toString().getBytes());
 
             is = new FileInputStream(file);
 
             byte[] buffer = new byte[1024 * 1024];
             int len = 0;
             while ((len = is.read(buffer)) != -1) {
   
                 os.write(buffer, 0, len);
             }
             os.write(LINE_END.getBytes());
             os.flush();
 
         } catch (Exception e) {
   
             throw new Exception(e);
         }
     }
 
     /** * 获取ContentType */
     public static String getContentType(File file) throws Exception {
   
         String streamContentType = "application/octet-stream";
         String imageContentType = "";
         ImageInputStream image = null;
         try {
   
             image = ImageIO.createImageInputStream(file);
             if (image == null) {
   
                 return streamContentType;
             }
             Iterator it = ImageIO.getImageReaders(image);
             if (it.hasNext()) {
   
                 imageContentType = "image/png";
                 return imageContentType;
             }
         } catch (IOException e) {
   
             throw new Exception(e);
         } finally {
   
             try {
   
                 if (image != null) {
   
                     image.close();
                 }
             } catch (IOException e) {
   
                 throw new Exception(e);
             }
 
         }
         return streamContentType;
     }
 
     public static void main(String[] args) throws Exception {
   
 
         String path = "E:\\NLP_study\\imgcode\\img\\test.png";
         System.out.println(imgcode_local(path));
         System.out.println(imgcode_online("http://www.bhshare.cn/test.png"));
         
         // 输出:
         // {"code":200,"msg":"ok","times":93,"data":"yemm"}
         // {"code":200,"msg":"ok","times":92,"data":"74689"}
     }
 }
  1. HTML/JavaScript实现

    网络图片识别:

正文到此结束
本文目录