这是一段生成网站验证码图片的JAVA代码 分享大家共同学习
package cn.com.view;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 这是一段生成验证码图片的例子
* @author yzsy0818
*
*/
public class CAPTCHA {
public static void main(String[] args) throws ImageFormatException, IOException {
CAPTCHA a =new CAPTCHA();
a.createImg();
}
/**
* @param args
* @throws IOException
* @throws ImageFormatException
*/
public void createImg() throws ImageFormatException, IOException {
// TODO 自动生成方法存根
int width = 100;
int height = 60;
int number = 4; // 显示多少个字符
String codes="ABCDEFGHIJKLMNOPGRSTUVWXYZ1234567890"; // 有哪些字符可供选择
// 创建一张图片
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// 创建白色背景
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 画黑边框
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
Random random = new Random();
// 每个字符占据的宽度
int x = (width - 1) / number;
int y = height - 4;
// 随机生成字符
for (int i = 0; i < number; i++) {
String code = String.valueOf(codes.charAt(random.nextInt(codes
.length())));
int red = random.nextInt(255);
int green = random.nextInt(255);
int blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
Font font = new Font("Arial", Font.PLAIN,
random(height / 2, height));
g.setFont(font);
g.drawString(code, i * x + 1, y);
System.out.println(code);
}
// 随机生成一些点
for (int i = 0; i < 30; i++) {
int red = random.nextInt(255);
int green = random.nextInt(255);
int blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
//g.drawOval(random.nextInt(width), random.nextInt(height), 1, 1);
g.fillRect(random.nextInt(width), random.nextInt(height), 2,2);
}
File file=new File("D:/X.jpg");
OutputStream out = new FileOutputStream(file,false);
// 将图片转换为JPEG类型
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
//out.flush();
out.close();
}
private int random(int min, int max) {
int m = new Random().nextInt(999999) % (max - min);
return m + min;
}
}