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 com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
@SuppressWarnings("restriction")
public class ImageUtil2 {
//设置画布宽度
private static int width=60;
private static int height=20;
public static Map<String ,BufferedImage> createImage(){
//画布
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//设置画笔
Graphics g=image.getGraphics();
//为画布涂色,给画笔上个颜色(随机验证码的背景颜色是随机的)
Random r=new Random();
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
//给画布涂色,给背景添加颜色
g.fillRect(0,0,width,height);
//添加几条干扰线看看(用黑色的线)
g.setColor(new Color(0,0,0));
for(int i=0;i<4;i++){
g.drawLine(r.nextInt(width),r.nextInt(height),r.nextInt(width),r.nextInt(height));
}
String imageCode=getNumber(4);
//画字符串,画验证码
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.setFont(new Font(null,Font.BOLD,18));
int k=5;
for (int i=0;i<4;i++){
g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
g.drawString(String.valueOf(imageCode.charAt(i)),k,19);
k=k+12;
}
Map<String,BufferedImage> map=new HashMap<String,BufferedImage>();
map.put(imageCode,image);
return map;
}
//应该是StringBuffer或者StringBuilder 不应该用这个String 提高效率啊效率
public static String getNumber(int num){
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random r=new Random();
String check="";
for(int i=0;i<num;i++){
check+=str.charAt(r.nextInt(36));
}
return check;
}
//将图片转换成流?
public static InputStream getInputStream(BufferedImage image)
throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(image);
byte[] imageBts = bos.toByteArray();
InputStream in = new ByteArrayInputStream(imageBts);
return in;
}
}
图片验证码工具类(struts中的运用)
最新推荐文章于 2024-06-30 01:03:40 发布