Java SWT Lable框中显示图片验证码

2 篇文章 0 订阅
2 篇文章 0 订阅

在使用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)));
 }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值