java swt label框中显示图片验证码

来源:互联网 发布:如何找到网站的数据库 编辑:程序博客网 时间:2024/05/06 08:27

//这是一个静态的方法可以直接调用

private static String testcode="";//验证码

public static void image(Label label) throws IOException{

               BufferedImage image = new BufferedImage(label.getSize().x, label.getSize().y,BufferedImage.TYPE_INT_RGB);//这里设置图片的大小
               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]);
                        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)));
 }
0 0
原创粉丝点击