import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.Icon;o m
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestBufferedImage {
private JFrame jf;
private JLabel jl;
public TestBufferedImage() {
Random random=new Random();``
jf=new JFrame();
//在内存中创建一个画图板
BufferedImage image=new BufferedImage(70,30,BufferedImage.TYPE_INT_RGB);
//获得画笔
Graphics graphics=image.getGraphics();
//设置画笔颜色
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
//画一个带填充色的矩形作为背景
graphics.fillRect(0, 0, 70, 30);
//设置画笔颜色
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
//设置字体
graphics.setFont(new Font("Courier New",Font.BOLD+Font.ITALIC,18));
//生成一个5位的随机字符串 [a,z][A,Z][0,9]
String s="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
StringBuffer code=new StringBuffer();
for (int i = 0; i < 5; i++) {
int index=random.nextInt(s.length());
code.append(s.charAt(index));
}
//将文字写到图片上
graphics.drawString(code.toString(), 5, 20);
//画3条干扰线
for (int i = 0; i < 3; i++) {
//设置画笔颜色
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
//画直线
graphics.drawLine(random.nextInt(71), random.nextInt(31), random.nextInt(71), random.nextInt(31));
}
Icon ic=new ImageIcon(image);
jl=new JLabel(ic);
}
private void init(){
jf.add(jl);
}
public void show(){
init();
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TestBufferedImage().show();
}
}