Java-JFrame窗體美化
JFrame默認的窗體比較土,可以通過一定的美化,讓窗體表現的比較漂亮,具體要根據設計的設計圖進行美化;
JFrame美化的大致思路:先將JFrame去除默認美化效果,實現JWindow效果,然后再JWindow基礎上對窗體的各項內容自定義設置與美化,大多用到插入背景圖片、添加各種鼠標事件、彈窗與輸入框等圓角等各種美化;
下面是一個登錄窗體的美化代碼,以后再有對窗體美化的可以參照一下代碼進行美化:
1、Login實體類代碼:
package com;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.geom.RoundRectangle2D;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JLabel;
import com.alibaba.fastjson.JSON;
import com.model.Message;
import com.model.User;
import com.sun.awt.AWTUtilities;
import com.util.FileUtils;
import com.util.MyButton;
import com.util.MyLineBorder;
import com.util.VerifyCodeUtils;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTextField;
import javax.swing.border.MatteBorder;
import javax.swing.JPasswordField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
/**
* 用戶登錄窗體(按照設計圖片效果制作)
* @author admin
*
*/
public class Login1{
private JFrame frame;//窗體
private JTextField userNameField;//用戶名輸入框
private JPasswordField passwordField;//密碼輸入框
private JTextField verifyCodeField;//驗證碼輸入框
private String verifyCode;//驗證碼圖片中的驗證碼值
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login1 window = new Login1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//將存儲驗證碼文件夾下的所有驗證碼圖片刪除
FileUtils.deleteAllFiles("./verifyCodeImg");
//自定義圓角輸入框邊界線
MyLineBorder myLineBorder = new MyLineBorder(new Color(192, 192, 192), 1 , true);
//只顯示輸入框的下邊框
MatteBorder bottomBorder = new MatteBorder(0, 0, 1, 0, new Color(192, 192, 192));
//設置JFrame禁用本地外觀,使用下面自定義設置的外觀;
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame();
frame.setBounds(0, 0, 300, 490);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
/**
* 對窗體進行基本設置
*/
//設置窗體在計算機窗口的中心部位顯示
frame.setLocationRelativeTo(frame.getOwner());
// 去掉窗口的裝飾
frame.setUndecorated(true);
//采用指定的窗口裝飾風格
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
//設置窗體圓角,最后兩個參數分別為圓角的寬度、高度數值,一般這兩個數值都是一樣的
AWTUtilities.setWindowShape(frame,
new RoundRectangle2D.Double(0.0D, 0.0D, frame.getWidth(), frame.getHeight(), 20.0D, 20.0D));
//設置背景顏色,記住一定要修改frame.getContentPane()的顏色,因為我們看到的都是這個的顏色而並不是frame的顏色
frame.getContentPane().setBackground(Color.white);
/**
* 插入頂部非凡汽車背景圖片
*/
//創建具有分層的JLayeredPane
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, -5, 300, 200);
frame.getContentPane().add(layeredPane);
// 創建圖片對象
ImageIcon img = new ImageIcon(Login1.class.getResource("/images/dingbu.jpg"));
//設置圖片在窗體中顯示的寬度、高度
img.setImage(img.getImage().getScaledInstance(300, 200,Image.SCALE_DEFAULT));
JPanel panel = new JPanel();
panel.setBounds(0, -5, 300, 200);
layeredPane.add(panel, JLayeredPane.DEFAULT_LAYER);
JLabel lblNewLabel = new JLabel("");
panel.add(lblNewLabel);
lblNewLabel.setIcon(img);
/**
* 插入窗體關閉的背景圖片及功能
*/
// 創建圖片對象
ImageIcon closeImg = new ImageIcon(Login1.class.getResource("/images/close.png"));
//設置圖片在窗體中顯示的寬度、高度
closeImg.setImage(closeImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));
JPanel closePanel = new JPanel();
closePanel.setBounds(269, -5, 31, 31);
layeredPane.add(closePanel,JLayeredPane.MODAL_LAYER);
JLabel closeLabel = new JLabel("");
closePanel.add(closeLabel);
closeLabel.setIcon(closeImg);
closeLabel.addMouseListener(new MouseAdapter() {
//鼠標點擊關閉圖片,實現關閉窗體的功能
@Override
public void mouseClicked(MouseEvent e) {
//dispose();
System.exit(0);//使用dispose();也可以關閉只是不是真正的關閉
}
//鼠標進入,換關閉的背景圖片
@Override
public void mouseEntered(MouseEvent e) {
// 創建圖片對象
ImageIcon closeImg1 = new ImageIcon(Login1.class.getResource("/images/mouse_close.png"));
//設置圖片在窗體中顯示的寬度、高度
closeImg1.setImage(closeImg1.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));
closeLabel.setIcon(closeImg1);
}
//鼠標離開,換關閉的背景圖片
@Override
public void mouseExited(MouseEvent e) {
// 創建圖片對象
ImageIcon closeImg = new ImageIcon(Login1.class.getResource("/images/close.png"));
//設置圖片在窗體中顯示的寬度、高度
closeImg.setImage(closeImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));
closeLabel.setIcon(closeImg);
}
});
/**
* 插入窗體最小化的背景圖片及功能
*/
// 創建圖片對象
ImageIcon minImg = new ImageIcon(Login1.class.getResource("/images/min.png"));
//設置圖片在窗體中顯示的寬度、高度
minImg.setImage(minImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));
JPanel minPanel = new JPanel();
minPanel.setBounds(237, -5, 31, 31);
layeredPane.add(minPanel,JLayeredPane.MODAL_LAYER);
JLabel minLabel = new JLabel("");
minLabel.addMouseListener(new MouseAdapter() {
//鼠標點擊最小化圖片,實現最小化窗體的功能
@Override
public void mouseClicked(MouseEvent e) {
frame.setExtendedState(JFrame.ICONIFIED);//最小化窗體
}
//鼠標進入,換最小化的背景圖片
@Override
public void mouseEntered(MouseEvent e) {
// 創建圖片對象
ImageIcon minImg1 = new ImageIcon(Login1.class.getResource("/images/mouse_min.png"));
//設置圖片在窗體中顯示的寬度、高度
minImg1.setImage(minImg1.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));
minLabel.setIcon(minImg1);
}
//鼠標離開,換最小化的背景圖片
@Override
public void mouseExited(MouseEvent e) {
// 創建圖片對象
ImageIcon minImg = new ImageIcon(Login1.class.getResource("/images/min.png"));
//設置圖片在窗體中顯示的寬度、高度
minImg.setImage(minImg.getImage().getScaledInstance(31, 31,Image.SCALE_DEFAULT));
minLabel.setIcon(minImg);
}
});
minPanel.add(minLabel);
minLabel.setIcon(minImg);
/**
* 插入用戶名輸入框前面的圖片
*/
// 創建圖片對象
ImageIcon userNameImg = new ImageIcon(Login1.class.getResource("/images/user_name.png"));
//設置圖片在窗體中顯示的寬度、高度
userNameImg.setImage(userNameImg.getImage().getScaledInstance(40, 40,Image.SCALE_DEFAULT));
JLabel userNameLabel = new JLabel("");
userNameLabel.setBounds(0, 220, 40, 40);
userNameLabel.setIcon(userNameImg);
//默認獲取光標
userNameLabel.setFocusable(true);
frame.getContentPane().add(userNameLabel);
/**
* 添加圓角的用戶名輸入框
*/
userNameField = new JTextField();
userNameField.setBounds(50, 220, 235, 50);
userNameField.setBorder(bottomBorder);
userNameField.setText(" 用戶名");
userNameField.setFont(new Font("微軟雅黑", 0, 14));
userNameField.setForeground(Color.GRAY);//默認設置輸入框中的文字顏色為灰色
userNameField.addFocusListener(new FocusAdapter() {
//獲取光標事件
@Override
public void focusGained(FocusEvent e) {
//獲取焦點時,輸入框中內容是“用戶名”,那么去掉輸入框中顯示的內容;
if("用戶名".equals((userNameField.getText().trim()))){
userNameField.setText("");
userNameField.setForeground(Color.black);//設置顏色為黑色
}
}
//失去光標事件
@Override
public void focusLost(FocusEvent e) {
//失去焦點時,如果輸入框中去掉空格后的字符串為空串則顯示用戶名
if("".equals((userNameField.getText().trim()))){
userNameField.setText(" 用戶名");
userNameField.setFont(new Font("微軟雅黑", 0, 14));
userNameField.setForeground(Color.GRAY);//默認設置輸入框中的文字顏色為灰色
}
}
});
frame.getContentPane().add(userNameField);
userNameField.setColumns(10);
/**
* 插入密碼輸入框前面的圖片
*/
// 創建圖片對象
ImageIcon passwordImg = new ImageIcon(Login1.class.getResource("/images/password.png"));
//設置圖片在窗體中顯示的寬度、高度
passwordImg.setImage(passwordImg.getImage().getScaledInstance(40, 40,Image.SCALE_DEFAULT));
JLabel passwordLabel = new JLabel("");
passwordLabel.setBounds(0, 280, 40, 40);
passwordLabel.setIcon(passwordImg);
frame.getContentPane().add(passwordLabel);
/**
* 添加圓角的密碼輸入框
*/
passwordField = new JPasswordField();
passwordField.setBounds(50, 280, 235, 50);
passwordField.setBorder(bottomBorder);
passwordField.setText(" 密碼");
passwordField.setFont(new Font("微軟雅黑", 0, 14));
passwordField.setForeground(Color.GRAY);//默認設置輸入框中的文字顏色為灰色
passwordField.setEchoChar((char)0);//顯示密碼輸入框中內容
passwordField.addFocusListener(new FocusAdapter() {
//獲取光標事件
@Override
public void focusGained(FocusEvent e) {
//獲取焦點時,輸入框中內容是“用戶名”,那么去掉輸入框中顯示的內容;
if("密碼".equals((passwordField.getText().trim()))){
passwordField.setText("");
passwordField.setEchoChar('*');//顯示密碼輸入框中內容
passwordField.setForeground(Color.black);//設置顏色為黑色
}
}
//失去光標事件
@Override
public void focusLost(FocusEvent e) {
//失去焦點時,如果輸入框中去掉空格后的字符串為空串則顯示用戶名
if("".equals((passwordField.getText().trim()))){
passwordField.setText(" 密碼");
passwordField.setFont(new Font("微軟雅黑", 0, 14));
passwordField.setForeground(Color.GRAY);//默認設置輸入框中的文字顏色為灰色
passwordField.setEchoChar((char)0);//顯示密碼輸入框中內容
}
}
});
frame.getContentPane().add(passwordField);
/**
* 插入驗證碼輸入框前面的圖片
*/
// 創建圖片對象
ImageIcon verifyCodeImg = new ImageIcon(Login1.class.getResource("/images/verify_code.png"));
//設置圖片在窗體中顯示的寬度、高度
verifyCodeImg.setImage(verifyCodeImg.getImage().getScaledInstance(40, 40,Image.SCALE_DEFAULT));
JLabel verifyCodeLabel = new JLabel("");
verifyCodeLabel.setBounds(0, 340, 40, 40);
verifyCodeLabel.setIcon(verifyCodeImg);
frame.getContentPane().add(verifyCodeLabel);
/**
* 添加圓角的驗證碼輸入框
*/
verifyCodeField = new JTextField();
verifyCodeField.setBounds(50, 340, 135, 50);
verifyCodeField.setBorder(bottomBorder);
verifyCodeField.setText(" 驗證碼");
verifyCodeField.setFont(new Font("微軟雅黑", 0, 14));
verifyCodeField.setForeground(Color.GRAY);//默認設置輸入框中的文字顏色為灰色
verifyCodeField.addFocusListener(new FocusAdapter() {
//獲取光標事件
@Override
public void focusGained(FocusEvent e) {
//獲取焦點時,輸入框中內容是“用戶名”,那么去掉輸入框中顯示的內容;
if("驗證碼".equals((verifyCodeField.getText().trim()))){
verifyCodeField.setText("");
verifyCodeField.setForeground(Color.black);//設置顏色為黑色
}
}
//失去光標事件
@Override
public void focusLost(FocusEvent e) {
//失去焦點時,如果輸入框中去掉空格后的字符串為空串則顯示用戶名
if("".equals((verifyCodeField.getText().trim()))){
verifyCodeField.setText(" 驗證碼");
verifyCodeField.setFont(new Font("微軟雅黑", 0, 14));
verifyCodeField.setForeground(Color.GRAY);//默認設置輸入框中的文字顏色為灰色
}
}
});
frame.getContentPane().add(verifyCodeField);
verifyCodeField.setColumns(10);
/**
* 添加驗證碼圖片
*/
JLabel verifyCodeImgLabel = new JLabel("");
verifyCodeImgLabel.setBounds(190, 340, 95, 50);
verifyCodeImgLabel.setBorder(myLineBorder);
frame.getContentPane().add(verifyCodeImgLabel);
//生成一張驗證碼圖片
verifyCode = VerifyCodeUtils.createOneCodeImage();
//將剛生成的驗證碼圖片顯示在窗體中去
ImageIcon verifyCodeSourceImg = new ImageIcon("./verifyCodeImg/"+verifyCode+".jpg");// 創建圖片對象
//設置圖片在窗體中顯示的寬度、高度
verifyCodeSourceImg.setImage(verifyCodeSourceImg.getImage().getScaledInstance(95, 50,Image.SCALE_DEFAULT));
verifyCodeImgLabel.setIcon(verifyCodeSourceImg);
//點擊驗證碼圖片,換一個新的驗證碼圖片
verifyCodeImgLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//刪除上一次的驗證碼圖片
File file = new File("./src/verifyCodeImg/"+verifyCode+".jpg");
if(file.exists()){
file.delete();
}
//生成一張新的驗證碼圖片
verifyCode = VerifyCodeUtils.createOneCodeImage();
ImageIcon verifyCodeSourceImg1 = new ImageIcon("./verifyCodeImg/"+verifyCode+".jpg");
verifyCodeSourceImg1.setImage(verifyCodeSourceImg1.getImage().getScaledInstance(95, 50,Image.SCALE_DEFAULT));
verifyCodeImgLabel.setIcon(verifyCodeSourceImg1);
}
});
/**
* 添加提示性信息的JLabel
*/
JLabel reminderMessage = new JLabel("",JLabel.CENTER);
reminderMessage.setBounds(15, 395, 270, 20);
reminderMessage.setForeground(Color.red);
reminderMessage.setFont(new Font("微軟雅黑", 0, 12));
frame.getContentPane().add(reminderMessage);
/**
* 添加圓角的提交按鈕
*/
MyButton myButton = new MyButton("安全登錄", 0);
myButton.setBounds(15, 420, 270, 50);
frame.getContentPane().add(myButton);
//設置窗體可見
frame.setVisible(true);
}
}
2、工具類FileUtils代碼:
package com.util;
import java.io.File;
/**
* 對文件操作的工具類
* @author admin
*
*/
public class FileUtils {
/**
* 刪除指定文件夾下的所有文件,此文件夾內只有文件,沒有任何文件夾
*/
public static Boolean deleteAllFiles(String filePath){
Boolean result = false;
File file = new File(filePath);
File temp = null;
if(file.exists()){
String [] tempList = file.list();
for (String string : tempList) {
temp = new File(filePath+"/"+string);
if(temp.isFile()){
temp.delete();
}
}
tempList = file.list();
if(tempList.length==0){
result = true;
}
}
return result;
}
public static void main(String[] args) {
Boolean result = FileUtils.deleteAllFiles("./verifyCodeImg");
System.out.println(result);
}
}
3、工具類MyButton代碼:
package com.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* 自定義帶有圓角的按鈕工具類
* @author admin
*
*/
public class MyButton extends JButton {
/* 決定圓角的弧度 */
public static int radius = 4;
public static Color COLOR1, COLOR2;
public static int pink = 3, ashen = 2, sky = 1, stone = 0;
/* 粉紅 */
public static Color pink1 = new Color(39, 121, 181);
public static Color pink2 = new Color(39, 121, 181);
/* 灰白 */
public static Color ashen1 = new Color(39, 121, 181);
public static Color ashen2 = new Color(39, 121, 181);
/* 深寶石藍 */
public static Color stone1 = new Color(39, 121, 181);
public static Color stone2 = new Color(39, 121, 181);
/* 淡天藍色 */
public static Color sky1 = new Color(39, 121, 181);
public static Color sky2 = new Color(39, 121, 181);
/* 光標進入按鈕判斷 */
private boolean hover;
public MyButton() {
this("", stone);
}
public MyButton(String name) {
this(name, stone);
}
public MyButton(String name, int style) {
super.setText(name);
if (style == pink) {
COLOR1 = pink1;
COLOR2 = pink2;
}
if (style == ashen) {
COLOR1 = ashen1;
COLOR2 = ashen2;
}
if (style == stone) {
COLOR1 = stone1;
COLOR2 = stone2;
}
if (style == sky) {
COLOR1 = sky1;
COLOR2 = sky2;
}
paintcolor(COLOR1, COLOR2);
}
private void paintcolor(Color COLOR1, Color COLOR2) {
setMargin(new Insets(0, 0, 0, 0));
setFont(new Font("微軟雅黑", 0, 14));
setBorderPainted(false);
setForeground(Color.white);
setFocusPainted(false);
setContentAreaFilled(false);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
int height = getHeight();
int with = getWidth();
float tran = 0.9F;
/*if (!hover) { 鼠標離開/進入時的透明度改變量
tran = 0.6F;
}*/
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
/* GradientPaint是顏色漸變類 */
GradientPaint p1;
GradientPaint p2;
if (getModel().isPressed()) {
p1 = new GradientPaint(0, 0, new Color(0, 0, 0), 0, height, new Color(100, 100, 100), true);
p2 = new GradientPaint(0, 1, new Color(0, 0, 0, 50), 0, height, new Color(255, 255, 255, 100), true);
} else {
p1 = new GradientPaint(0, 0, new Color(100, 100, 100), 0, height, new Color(0, 0, 0), true);
p2 = new GradientPaint(0, 1, new Color(255, 255, 255, 100), 0, height, new Color(0, 0, 0, 50), true);
}
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, tran));
RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0, 0, with - 1, height - 1, radius, radius);
// 最后兩個參數數值越大,按鈕越圓,以下同理
Shape clip = g2d.getClip();
g2d.clip(r2d);
GradientPaint gp = new GradientPaint(0.0F, 0.0F, COLOR1, 0.0F, height / 2, COLOR2, true);
g2d.setPaint(gp);
g2d.fillRect(0, 0, with, height);
g2d.setClip(clip);
g2d.setPaint(p1);
g2d.drawRoundRect(0, 0, with - 3, height - 3, radius, radius);
g2d.setPaint(p2);
g2d.drawRoundRect(1, 1, with - 3, height - 3, radius, radius);
g2d.dispose();
super.paintComponent(g);
}
public static void main(String args[]) {
JFrame frm = new JFrame();
MyButton but = new MyButton("圓角JButton", 0);
frm.setLayout(null);
frm.setBounds(800, 400, 500, 200);
but.setBounds(30, 30, 200, 50);
frm.add(but);
frm.setDefaultCloseOperation(3);
frm.setVisible(true);
}
}
4、工具類MyLineBorder代碼:
package com.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.border.LineBorder;
/**
* 為創建圓角輸入框自定義邊框線條工具類
* @author admin
*
*/
public class MyLineBorder extends LineBorder{
private static final long serialVersionUID = 1L;
public MyLineBorder(Color color, int thickness, boolean roundedCorners) {
super(color, thickness, roundedCorners);
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Color oldColor = g.getColor();
Graphics2D g2 = (Graphics2D)g;
int i;
g2.setRenderingHints(rh);
g2.setColor(lineColor);
for(i = 0; i < thickness; i++) {
if(!roundedCorners)
g2.drawRect(x+i, y+i, width-i-i-1, height-i-i-1);
else
g2.drawRoundRect(x+i, y+i, width-i-i-1, height-i-i-1, 10, 10); //就是這一句 ,后兩個參數控制圓角的大小
}
g2.setColor(oldColor);
}
}
5、工具類VerifyCodeUtils代碼:
package com.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 生成驗證碼圖片的工具類
* @author admin
*
*/
public class VerifyCodeUtils {
// 使用到Algerian字體,系統里沒有的話需要安裝字體,字體只顯示大寫,去掉了1,0,i,o幾個容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 使用系統默認字符源生成驗證碼
*
* @param verifySize
* 驗證碼長度
* @return
*/
public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成驗證碼
*
* @param verifySize
* 驗證碼長度
* @param sources
* 驗證碼字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources) {
if (sources == null || sources.length() == 0) {
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
/**
* 生成隨機驗證碼文件,並返回驗證碼值
*
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 輸出隨機驗證碼圖片流,並返回驗證碼值
*
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 生成指定驗證碼圖像文件
*
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
if (outputFile == null) {
return;
}
File dir = outputFile.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
try {
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch (IOException e) {
throw e;
}
}
/**
* 輸出指定驗證碼圖片流
*
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA,
Color.ORANGE, Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 設置邊框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 設置背景色
g2.fillRect(0, 2, w, h - 4);
// 繪制干擾線
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 設置線條的顏色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪點
float yawpRate = 0.05f;// 噪聲率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使圖片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1),
(w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
//生成一張驗證碼圖片,並保存到項目的verifyCodeImg文件夾下
public static String createOneCodeImage(){
String imgName = "";
try {
File dir = new File("./verifyCodeImg");
int w = 95, h = 50;
String verifyCode = generateVerifyCode(4);
File file = new File(dir, verifyCode + ".jpg");
outputImage(w, h, file, verifyCode);
imgName = verifyCode;
} catch (IOException e) {
imgName = "";
e.printStackTrace();
}finally{
return imgName;
}
}
public static void main(String[] args) throws IOException {
String codeImage = VerifyCodeUtils.createOneCodeImage();
System.out.println(codeImage);
}
}
