个性IP图[JAVA]

在网络上,可以看到一些论坛,一些网站上出现的个性的签名档。上面标注着你的IP,你的操作系统,你的浏览器以及你所在的位置。

当然网络上也有一些这类源码文件下载!

但大部分的都是php制作的,当然我也制作过php版的,然而今天就想到用Java也写一份玩玩。

ip.png

由于获取的User-Agent比较难解析,然后为了方便就调用了UserAgentUtils组件来解析:


 <dependency>
       <groupid>nl.bitwalker</groupid>
       <artifactid>UserAgentUtils</artifactid>
       <version>1.2.4</version>
  </dependency>


代码:

 /**
     * IP个性图片
     * @param request 要获取的request
     * @param srcImgPath 源图片路径
     * @param degree 旋转角度
     * @param color  字体颜色
     */
    public static BufferedImage GxIpImg(HttpServletRequest request, String srcImgPath, Integer degree, Color color) {
        InputStream is = null;
        OutputStream os = null;
        String ip = GetIp(request);
        //获取浏览器信息
        String ua = request.getHeader("User-Agent");
        //转成UserAgent对象
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        //获取系统信息(大写)
        OperatingSystem oss = userAgent.getOperatingSystem();
        //获取浏览器信息(大写)
        Browser browser = userAgent.getBrowser();
        //系统名称
        String system = oss.getName();
        System.out.println("系统名称"+system);
        //浏览器名称
        String browserName = browser.getName();
        System.out.println("浏览器名称"+browserName);
        try {
            // 1、源图片
            java.awt.Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), java.awt.Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree),  buffImg.getWidth()/2,buffImg.getHeight() /2);
            }
            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(new java.awt.Font("宋体", java.awt.Font.BOLD, buffImg.getHeight() /13));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.15f));
            // 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
            Integer width = buffImg.getWidth();//取图片宽
            Integer height = buffImg.getHeight();//取图片高
            g.drawString("IP:"+ip,  width /2.30f, height/3.50f);
            g.drawString("地点:"+GetIpPath(ip),  width /2.30f, height/2.50f);
            g.drawString("系统名称:"+system,   width /2.30f,  height/2.00f);
            g.drawString("浏览器名称:"+browserName,  width /2.30f, height/1.70f);
            g.drawString("当前时间:"+GetTime("yyyy-MM-dd"),  width /2.30f, height/1.40f);
            // 9、释放资源
            g.dispose();
            // 10、返回图片
            return buffImg;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
	/**
     * 获取WEB访问IP
     * @param request
     * @return
     */
    public static String GetIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        System.out.println("x-forwarded-for ip: " + ip);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值,第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            System.out.println("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            System.out.println("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            System.out.println("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            System.out.println("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            System.out.println("getRemoteAddr ip: " + ip);
        }
        System.out.println("获取客户端ip: " + ip);
        return ip;
    }
    /**
     * 获取IP地理位置
     * @param ip 需要查询的IP
     * @return
     */
    public static String GetIpPath(String ip){
        String html = GetURL_Get("http://ip138.com/ips138.asp?ip="+ip,"GB2312");
        //置入正则方式
        Pattern pn = Pattern.compile("本站数据:(.*?)</li>");
        //置入需要匹配的数据
        Matcher matcher = pn.matcher(html);
        String result="";
        while (matcher.find()) {
            result = matcher.group(1);
        }
        if(result.equals("")){
            return "获取失败";
        }
        return result.replaceAll(" ", "");
    }    
	/**
     * GET网页访问
     * @param urls 要获取网页的链接
     * @param encoded 编码方式,默认UTF-8
     * @return
     */
    public static String GetURL_Get(String urls,String encoded) {
        StringBuffer jg = new StringBuffer();
        try {
            URL url = new URL(urls);
            System.out.println("URL 为:" + url.toString());
            System.out.println("协议为:" + url.getProtocol());
            System.out.println("验证信息:" + url.getAuthority());
            System.out.println("文件名及请求参数:" + url.getFile());
            System.out.println("主机名:" + url.getHost());
            System.out.println("路径:" + url.getPath());
            System.out.println("端口:" + url.getPort());
            System.out.println("默认端口:" + url.getDefaultPort());
            System.out.println("请求参数:" + url.getQuery());
            System.out.println("定位位置:" + url.getRef());
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时
            connection.setConnectTimeout(3*1000);
            //设置请求头
            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            //获取输入流
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            byte[] b = new byte[1024];
            int len = 0;
            if(encoded.equals("")){
                encoded="UTF-8";
            }
            while((len = bis.read(b)) != -1){
                jg.append(new String(b, 0, len,encoded));
            }
            bis.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jg.toString();
    }
    /**
     * 获取当前时间
     * @param Format 获取的时间格式,如"yyyy-MM-dd"。
     * @return
     */
    public static String GetTime(String Format){
        Date dasj = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(Format);
        dasj.clone();
        return sdf.format(dasj);
    }

使用方法:


BufferedImage img = GxIpImg(request,"F:/ip.png",0,new Color(255, 19, 19, 225));
response.setContentType("image/png");
ServletOutputStream out = response.getOutputStream();
ImageIO.write(img,"png",out);


转载请注明出处凌夕博客 »漫小猫原文地址《个性IP图[JAVA]

相关推荐

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(1)

路过来一脚
武陵红苗 Google Chrome 63.0.3239.132 Windows 7 5年前 (2019-08-03) 回复
湖南省邵阳市 移动湖南省邵阳市 移动