2015-03-10 15:18

[Java] 產生驗證碼圖片

  1. import java.awt.Color; 
  2. import java.awt.Font; 
  3. import java.awt.Graphics; 
  4. import java.awt.image.BufferedImage; 
  5. import java.io.File; 
  6. import java.util.Random; 
  7.  
  8. import javax.imageio.ImageIO; 
  9.  
  10. public class TestCaptchaImage { 
  11.  
  12.    public static void main(String[] args) throws Exception { 
  13.        String captcha = "09875"; 
  14.  
  15.        int width = 55; 
  16.        int height = 20; 
  17.        Color fontColor = new Color(36, 85, 92); /*文字顏色*/ 
  18.        Color lineColor = new Color(65, 161, 175); /*線條顏色*/ 
  19.        Color bgColor = new Color(208, 226, 229); /*底色*/ 
  20.  
  21.        Random random = new Random(); 
  22.        random.setSeed(System.currentTimeMillis()); 
  23.  
  24.        BufferedImage image = new BufferedImage( 
  25.            width, height, BufferedImage.TYPE_INT_RGB 
  26.        ); 
  27.        Graphics g = image.getGraphics(); 
  28.  
  29.        /* 底色 */ 
  30.        g.setColor(bgColor); 
  31.        g.fillRect(0, 0, width, height); 
  32.  
  33.        /* 畫線 */ 
  34.        g.setColor(lineColor); 
  35.        for (int i=0; i < 20; i++) { 
  36.            g.drawLine( 
  37.                random.nextInt(width), 0, 
  38.                random.nextInt(width), height 
  39.            ); 
  40.        } 
  41.  
  42.        /* 畫出文字 */ 
  43.        g.setFont(new Font("Atlantic Inline", Font.BOLD, 20)); 
  44.        g.setColor(fontColor); 
  45.        g.drawString(captcha, 0, 18); 
  46.  
  47.        /* 畫線 */ 
  48.        g.setColor(lineColor); 
  49.        for (int i=0; i < 4; i++) { 
  50.            g.drawLine( 
  51.                0, random.nextInt(height), 
  52.                width, random.nextInt(height) 
  53.            ); 
  54.        } 
  55.  
  56.        g.dispose(); 
  57.  
  58.        ImageIO.write(image, "png", new File("captcha_image.png")); 
  59.    } 
  60. } 

參考文件:
Graphics (Java 2 Platform SE 6)

0 回應: