6 扭曲验证码

来源:互联网 发布:淘宝内部优惠券靠谱吗? 编辑:程序博客网 时间:2024/05/01 05:55


  • 多的就不说了,下面为大家介绍新的验证码噪声,扭曲。

  • 代码如下,生成的验证码应该如页面的图像所示。

package img;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;/* * 日期:2016年10月18日:下午6:01:53 * 程序作用:加入扭曲字符**/public class CheckCode2 {    public static BufferedImage getCode() {        // 生成图片        int ImgWidth = 120;        int ImgHeight = 30;        BufferedImage img = new BufferedImage(ImgWidth, ImgHeight, BufferedImage.TYPE_INT_BGR);        // 转成可以画扭曲字符的画笔        Graphics2D g = (Graphics2D) img.getGraphics();        // 灰色        g.setColor(Color.GRAY);        // 填充画布        g.fillRect(0, 0, ImgWidth, ImgHeight);        // 蓝色        g.setColor(Color.BLUE);        // 边框        g.drawRect(0, 0, ImgWidth - 1, ImgHeight - 1);        // 数据 4个字符        String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";        // random对象        Random random = new Random();        // void rotate(double,theta,double x,double y)        // theta 弧度=jiaodu*Math.PI/180        //                 // 字的颜色        g.setColor(Color.YELLOW);        // 字体        g.setFont(new Font("隶书", Font.BOLD, 20));        // 随机获取下标 随机写字体        int x = 20;        int y = 20;        for (int i = 0; i < 4; i++) {            // 生成随机数得到随机字符            int index = random.nextInt(words.length());            char ch = words.charAt(index);            // 生成随机弧度            int jiaodu=random.nextInt(60)-30;// 角度正负30度            double hudu=jiaodu*Math.PI/180;// 弧度            //             g.rotate(hudu,x,y);            // 画字符串            g.drawString("" + ch, x, y);            // 会累计旋转 所以要转回去            g.rotate(-hudu,x,y);            x += 20;        }        return img;    }    public static void main(String[] args) throws IOException {        BufferedImage img = getCode();        ImageIO.write(img, "jpg", new File("src/img/CheckCode2.jpg"));    }}

0 0
原创粉丝点击