java图片验证码_Java实现图片验证码

创建生成验证码图片的工具类:

import javax.imageio.ImageIO;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.Random;

/**

* 验证码生成器

*

*/

public class SCaptcha {

// 图片的宽度。

private int width = 120;

// 图片的高度。

private int height = 40;

// 验证码字符个数

private int codeCount = 4;

// 验证码干扰线数

private int lineCount = 50;

// 验证码

private String code = null;

// 验证码图片Buffer

private BufferedImage buffImg = null;

private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'P', 'Q', 'R',

'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };

// 生成随机数

private Random random = new Random();

public SCaptcha() {

this.createCode();

}

/**

*

* @param width 图片宽

* @param height 图片高

*/

public SCaptcha(int width, int height) {

this.width = width;

this.height = height;

this.createCode();

}

/**

*

* @param width 图片宽

* @param height 图片高

* @param codeCount 字符个数

* @param lineCount 干扰线条数

*/

public SCaptcha(int width, int height, int codeCount, int lineCount) {

this.width = width;

this.height = height;

this.codeCount = codeCount;

this.lineCount = lineCount;

this.createCode();

}

public void createCode() {

int codeX = 0;

int fontHeight = 0;

fontHeight = height - 5;// 字体的高度

codeX = width / (codeCount 3);// 每个字符的宽度

// 图像buffer

buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics2D g = buffImg.createGraphics();

// 将图像填充为白色

g.setColor(Color.WHITE);

g.fillRect(0, 0, width, height);

// 创建字体

ImgFontByte imgFont = new ImgFontByte();

Font font = imgFont.getFont(fontHeight);

g.setFont(font);

StringBuffer randomCode = new StringBuffer();

// 随机产生验证码字符

for (int i = 0; i < codeCount; i ) {

String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);

// 设置字体颜色

g.setColor(getRandomColor());

// 设置字体位置

g.drawString(strRand, (i 1) * codeX, getRandomNumber(height / 2) 25);

randomCode.append(strRand);

}

code = randomCode.toString();

}

/** 获取随机颜色 */

private Color getRandomColor() {

int r = getRandomNumber(255);

int g = getRandomNumber(255);

int b = getRandomNumber(255);

return new Color(r, g, b);

}

/** 获取随机数 */

private int getRandomNumber(int number) {

return random.nextInt(number);

}

public void write(String path) throws IOException {

OutputStream sos = new FileOutputStream(path);

this.write(sos);

}

public void write(OutputStream sos) throws IOException {

ImageIO.write(buffImg, "png", sos);

sos.close();

}

public BufferedImage getBuffImg() {

return buffImg;

}

public String getCode() {

return code;

}

/** 字体样式类 */

class ImgFontByte {

public Font getFont(int fontHeight) {

try {

Font baseFont = Font.createFont(Font.HANGING_BASELINE, new ByteArrayInputStream(

hex2byte(getFontByteStr())));

return baseFont.deriveFont(Font.PLAIN, fontHeight);

} catch (Exception e) {

return new Font("Arial", Font.PLAIN, fontHeight);

}

}

private byte[] hex2byte(String str) {

if (str == null)

return null;

str = str.trim();

int len = str.length();

if (len == 0 || len % 2 == 1)

return null;

byte[] b = new byte[len / 2];

try {

for (int i = 0; i < str.length(); i = 2) {

b[i / 2] = (byte) Integer.decode("0x" str.substring(i, i 2)).intValue();

}

return b;

} catch (Exception e) {

return null;

}

}

// 字体文件的十六进制字符串

private String getFontByteStr() {

//防止报字符串长度过长错误,改为从配置文件读取

return ReadFontByteProperties.getFontByteStr();

}

}

}

controller层代码:

// 设置响应的类型格式为图片格式

response.setContentType("image/jpeg");

// 禁止图像缓存。

response.setHeader("Pragma", "no-cache");

response.setHeader("Cache-Control", "no-cache");

response.setDateHeader("Expires", 0);

//实例生成验证码对象

SCaptcha instance = new SCaptcha();

//将验证码存入session

request.getSession().setAttribute("verification", instance.getCode());

//向页面输出验证码图片

instance.write(response.getOutputStream());

页面代码:

verification

效果如下:

165606449_1_2019070902362285.png

如果想实现点击刷新图片,则将页面代码改至如下:

login_verification.action

添加js代码:

function changeCodeImg(){

var num=Math.ceil(Math.random()*10);//生成一个随机数(防止缓存)

var src = $("#vimg")[0].src;

//alert(src "?num=" num);

$("#vimg").attr('src',src "?num=" num);

}

这样就OK了。

来源:https://www.icode9.com/content-1-311401.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java 图片滑动验证码的示例代码,使用 Java Swing 库实现: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class ImageSliderVerificationCode extends JFrame { private static final long serialVersionUID = 1L; private final int WIDTH = 400; private final int HEIGHT = 300; private final int BLOCK_SIZE = 50; private Image bgImage; private Image blockImage; private int blockX; private int blockY; private int mouseX; private int mouseY; private boolean isDragging; public ImageSliderVerificationCode() { setTitle("Image Slider Verification Code"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setLocationRelativeTo(null); bgImage = new ImageIcon("background.jpg").getImage(); blockImage = new ImageIcon("block.png").getImage(); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.getX() >= blockX && e.getX() <= blockX + BLOCK_SIZE && e.getY() >= blockY && e.getY() <= blockY + BLOCK_SIZE) { isDragging = true; mouseX = e.getX(); mouseY = e.getY(); } } public void mouseReleased(MouseEvent e) { isDragging = false; if (blockX >= WIDTH - BLOCK_SIZE) { JOptionPane.showMessageDialog(null, "Verification passed!"); System.exit(0); } else { blockX = 0; blockY = new Random().nextInt(HEIGHT - BLOCK_SIZE); repaint(); } } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { if (isDragging) { blockX += e.getX() - mouseX; blockY += e.getY() - mouseY; if (blockX < 0) { blockX = 0; } if (blockX > WIDTH - BLOCK_SIZE) { blockX = WIDTH - BLOCK_SIZE; } if (blockY < 0) { blockY = 0; } if (blockY > HEIGHT - BLOCK_SIZE) { blockY = HEIGHT - BLOCK_SIZE; } mouseX = e.getX(); mouseY = e.getY(); repaint(); } } }); } public void paint(Graphics g) { g.drawImage(bgImage, 0, 0, null); g.drawImage(blockImage, blockX, blockY, null); } public static void main(String[] args) { ImageSliderVerificationCode verCode = new ImageSliderVerificationCode(); verCode.setVisible(true); } } ``` 此代码将生成一个包含背景图片和滑块图片的窗口。当用户按住滑块图片并拖动它时,窗口将显示移动后的滑块图片。如果用户将滑块图片拖动到窗口的右边缘,则显示验证通过的消息并退出程序。否则,滑块图片将被重置到窗口的左侧,并随机在窗口的垂直方向上移动。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值