java生成验证码

package com.tarena.util;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


import org.apache.taglibs.standard.tag.common.core.SetSupport;

//java的拓展包,官方API找不到
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.tarena.action.BaseAction;


public class ImageUtil{

private static final char[] chars = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','L','p','U' };
private static final int SIZE = 4;
private static final int LINES = 5;
private static final int WIDTH = 52;
private static final int HEIGHT = 33;
private static final int FONT_SIZE = 30;

/**
* 用于生成一个图片,图片中带有验证码。
* Map的key存的是验证码字符串,
* Map的value存的是图片。
*/
public static Map<String,BufferedImage> createImage(){
StringBuffer sb = new StringBuffer();
BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.LIGHT_GRAY);
//画背景
g.fillRect(0, 0, WIDTH, HEIGHT);
Random ran = new Random();
// 画随机字符
for (int i = 1; i <= SIZE; i++) {
int r = ran.nextInt(chars.length);
g.setColor(getRandomColor());
g.setFont(new Font(null, Font.BOLD + Font.ITALIC, FONT_SIZE));
g.drawString(chars[r] + "", (i - 1) * WIDTH / SIZE,HEIGHT / 2);
sb.append(chars[r]);
}

// 画干扰线
for (int i = 1; i <= LINES; i++) {
g.setColor(getRandomColor());
g.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
Map<String,BufferedImage> map = new HashMap<String, BufferedImage>();
map.put(sb.toString(), image);
return map;
}


private static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256), ran.nextInt(256),ran.nextInt(256));
return color;
}

public static InputStream getInputStream(BufferedImage image)throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// JPEGImageEncoder可适用于其他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);

byte[] imageBts = bos.toByteArray();
InputStream in = new ByteArrayInputStream(imageBts);
return in;

}
}
阅读更多 登录后自动展开
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页