在使用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)));
}