package com.ak.util;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
/**
* 驗證碼工具類
*
* @author Akeung
* 2019/12/11 0011
*/
public class ImageVerifyCodeUtil {
private static final Random random = new Random();
private static final String[] fontNames = {"宋體", "華文楷體", "黑體", "微軟雅黑", "楷體_GB2312", "Georgia"};
public static String drawImage(ByteArrayOutputStream output) {
String code;
int width = 60;
int height = 30;
//創建圖片緩衝區
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = bi.createGraphics();
//設置背景顏色
g.setBackground(new Color(255, 255, 255));
g.clearRect(0, 0, width, height);
StringBuilder stringBuilder = new StringBuilder();
//這裏只畫入四個字符
for (int i = 0; i < 4; i++) {
String s = randomChar() + ""; //隨機生成字符,因爲只有畫字符串的方法,沒有畫字符的方法,所以需要將字符變成字符串再畫
stringBuilder.append(s); //添加到StringBuilder裏面
float x = i * 1.0F * width / 4; //定義字符的x座標
g.setFont(randomFont()); //設置字體,隨機
g.setColor(randomColor()); //設置顏色,隨機
g.drawString(s, x, height-8);
}
code = stringBuilder.toString();//獲取驗證碼字符串
//定義干擾線的數量(5條)
Graphics2D graphics = (Graphics2D) bi.getGraphics();
for (int i = 0; i < 5; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
int x2 = random.nextInt(width);
int y2 = random.nextInt(height);
graphics.setColor(randomColor());
graphics.drawLine(x1, y1, x2, y2);
}
// 釋放圖形上下文
g.dispose();
try {
ImageIO.write(bi, "png", output);
} catch (IOException e) {
e.printStackTrace();
}
return code;
}
//隨機字體
private static Font randomFont() {
int index = random.nextInt(fontNames.length);
String fontName = fontNames[index];
int style = random.nextInt(4); //隨機獲取4種字體的樣式
int size = random.nextInt(20) % 6 + 15; //隨機獲取字體的大小(15-20之間的值)
return new Font(fontName, style, size);
}
//隨機顏色
private static Color randomColor() {
int r = random.nextInt(225);
int g = random.nextInt(225);
int b = random.nextInt(225);
return new Color(r, g, b);
}
//隨機字符
private static char randomChar() {
//A-Z,a-z,0-9,可剔除一些難辨認的字母與數字
String str = "0123456789ABCdefghiDEFGHIJopPQRVWXYZabcjklSTUmnqrstKLMNOvuwxyz";
return str.charAt(random.nextInt(str.length()));
}
public static void main(String[] args) throws IOException {
File file = new File("D://code.png");
FileOutputStream fileOutputStream = new FileOutputStream(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String s = drawImage(byteArrayOutputStream);
System.out.println(s);
byteArrayOutputStream.writeTo(fileOutputStream);
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
}
}