登录验证码的生成Java代码
package example7;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
//第一种方法
class image{
public static void main(String[] args) throws IOException, Exception {
//得到图片缓冲区
BufferedImage img=new BufferedImage(120, 60,BufferedImage.TYPE_INT_RGB);
//得到它的绘制环境(这张图片的笔)
Graphics2D g1=(Graphics2D) img.getGraphics();
//设置图片背景颜色
g1.setColor(Color.WHITE);
//填充整个图片
g1.fillRect(0, 0, 120, 60);
//设置边框颜色
g1.setColor(Color.RED);
g1.drawRect(0, 0, 120-1, 60-1);
//设置字体
g1.setFont(new Font("宋体",Font.BOLD,40));
//设置字体颜色
g1.setColor(Color.black);
String s="";
for(int i=0;i<4;i++) {
s=s+rand();
}
//像图片上写入字符串
g1.drawString(s, 35,35);
System.out.println(s);
//保存图片
ImageIO.write(img,"JPEG", new FileOutputStream("d:/a.jpg"));
}
public static String rand() {
Random ran1 = new Random();
for (int i = 0; i < 4; i++) {
return(ran1.nextInt(4)+"");
}
return null;
}
}
//第二种方法
首先,需要引入itcast-tools-1.4.2.jar包
然后代码如下:
package example7;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import cn.itcast.vcode.utils.VerifyCode;
class image1 {
public static void main(String[] args) throws Exception {
test1();
}
public static void test1() throws Exception, Exception {
VerifyCode verifycode = new VerifyCode();
BufferedImage bi = verifycode.getImage(); //随机的
System.out.println(verifycode.getText());//打印图片上的内容
VerifyCode.output(bi, new FileOutputStream("d:/s.jpg"));
}
}