2013/01/12

Java 圖形驗證碼

驗證碼再網頁上還蠻常見的,大多用於認證
這次實做方法透過Java Graphics2D的類別來建構
官方說法是provide more sophisticated control over geometry, coordinate transformations, color management, and text layout.

寫法就直接看下面吧,註解都寫好了
如果沒寫到的話,去找Google大神吧



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class NumberImage {

    public static void main(String[] args) {
        new NumberImage().init();
    }

    private void init() {
        BufferedImage bufferedImage = new BufferedImage(70, 40,
                BufferedImage.TYPE_INT_RGB); // 設定影像大小
        Graphics2D graphics2d = bufferedImage.createGraphics();
        graphics2d.setColor(Color.PINK); // 設定字體顏色
        graphics2d.fillRect(10, 10, 50, 20); // 設定方塊畫圖位址
        graphics2d.setColor(Color.GREEN);
        String str = "123456";
        graphics2d.setFont(new Font("Default", Font.BOLD, 13)); // 設定字體種類
        graphics2d.drawString(str, 15, 25); // 將該字串寫入,並且設定繪圖位址
        try {
            ImageIO.write(bufferedImage, "jpeg", new File("test.jpeg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

有點模糊的字體,這應該是JPEG的特點吧


參考文章:
http://www.javaworld.com.tw/jute/post/view?bid=6&id=2019&tpg=1&ppg=1&sty=1&age=0