Java验证码图片生成源代码
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;
public class Captchautil {
public static String random() {
StringBuffer stringBuffer = new StringBuffer ();
String arrWord = "abcdefghigklmnopqrstuvwxyz";
String allCase = arrWord.toUpperCase () + arrWord + "1234567890";
byte[] bytes = allCase.getBytes ();
Random random = new Random ();
for (int i = 0; i < 4; i++) {
int index = random.nextInt (bytes.length + 1);
stringBuffer.append ((char)bytes[index]);
}
return stringBuffer.toString ();
}
public static void outputImage(String code, OutputStream ops) {
Random random = new Random ();
BufferedImage image = new BufferedImage (100, 40, BufferedImage.TYPE_3BYTE_BGR);
Graphics graphics = image.getGraphics ();
graphics.setColor (Color.white);
graphics.fillRect (0, 0, 100, 40);
byte[] bytes = code.getBytes ();
graphics.setColor (new Color (random.nextInt (255) + 1,
random.nextInt (255) + 1,
random.nextInt (255) + 1));
graphics.setFont (new Font ("微软雅黑", Font.PLAIN, 20));
graphics.drawBytes (bytes, 0, 4, 20, 20);
for (int i = 0; i < 10; i++) {
graphics.setColor (new Color (random.nextInt (255) + 1,
random.nextInt (255) + 1,
random.nextInt (255) + 1));
graphics.drawLine (random.nextInt (100),
random.nextInt (40),
random.nextInt (100),
random.nextInt (40));
}
try {
boolean write = ImageIO.write (image, "png", ops);
System.out.println (write);
} catch (IOException e) {
e.printStackTrace ();
}
}
public static void main(String[] args){
String code = random ();
System.out.println (code);
try {
OutputStream sot = new FileOutputStream ("I:\\file\\a.png", false);
outputImage (code, sot);
} catch (FileNotFoundException e) {
e.printStackTrace ();
}
}
}