在使用Java GUI在做一些登录界面的时候我们可能需要一些验证码,下面的这个方法适用于Java SWT,用于在Lable框中显示图片验证码。
public static String testcode="";//验证码,保存验证码,取这个值于用户输入的值作比较
public static void image(Label label) throws IOException{
//BufferedImage 的构造函数可以设置图片的大小
BufferedImage image = new BufferedImage(label.getSize().x, label.getSize().y,BufferedImage.TYPE_INT_RGB);//这里设置图片的大小
//这里需要使用到java.awt.Graphics来绘制图片
java.awt.Graphics graphics = image.getGraphics();
Color color = new Color(245, 245, 220);
graphics.setColor(color);//为图片添加的底色
graphics.fillRect(0,0,label.getSize().x,label.getSize().y);
char[] content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
Random random = new Random();
int index;
for(int i=0;i<4;i++){//验证码长度
index = random.nextInt(content.length);
testcode+=String.valueOf(content[index]);//testcode是验证码
//图片中文字的颜色
graphics.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
//图片中文字的位置
graphics.drawString(content[index]+"",10+20*i,10+3*random.nextInt(4));
//1,验证码文字,2文字距离上边的距离3,距离下部分的距离,可以更改这后面的两个数据,来改变图片的,验证码显示位置
}
ByteArrayOutputStream stream=new ByteArrayOutputStream();
ImageIO.write(image, "jpg", stream);
InputStream inputStream=new ByteArrayInputStream(stream.toByteArray());
label.setImage(new Image(null, new ImageData(inputStream).scaledTo(label.getSize().x, label.getSize().y)));
}