package com.sinosoft.vfs.util;
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;
/**
* 这是一段生成验证码图片的例子
*
*
*/
public class EnsureCodeUtil{
private static EnsureCodeUtil instance = null;
private static Object obj = new Object();
private String strcode="";
private EnsureCodeUtil(){}
public static EnsureCodeUtil getInstance(){
if(instance==null){
synchronized(obj){
instance = new EnsureCodeUtil();
}
}
return instance;
}
public static void main(String[] args) throws ImageFormatException,
IOException {
EnsureCodeUtil.getInstance().createImg("e:/123.jpg",140,40,6);
//a.createImg("e:/123.jpg",140,40,6);
}
/**
* @param args
* @throws IOException
* @throws ImageFormatException
*/
public String createImg(String filepath,int width,int height,int number) throws ImageFormatException, IOException {
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;
StringBuilder code_temp = new StringBuilder();
// 随机生成字符
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);
code_temp.append(code);
}
strcode = code_temp.toString();
// 随机生成一些点
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(filepath);
OutputStream out = new FileOutputStream(file);
// 将图片转换为JPEG类型
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.flush();
out.close();
return strcode;
}
private int random(int min, int max) {
int m = new Random().nextInt(999999) % (max - min);
return m + min;
}
}