目录 过程介绍 创建一个 `BufferedImage` 对象 创建一个 `Graphics2D` 对象 绘制字符和干扰线 将生成的图像保存到文件 示例代码
过程介绍
创建一个 BufferedImage
对象
首先创建一个 BufferedImage
对象来表示图像
创建一个 Graphics2D
对象
然后使用 createGraphics()
方法创建一个 Graphics2D
对象
绘制字符和干扰线
将生成的图像保存到文件
使用 ImageIO.write()
方法将生成的图像保存到文件中,或者将其输出到控制台。
示例代码
import java. awt. * ;
import java. awt. image. BufferedImage ;
import java. util. Random ; public class CaptchaGenerator { private static final String CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ; private static final int WIDTH = 160 ; private static final int HEIGHT = 50 ; private static final int CHAR_NUM = 4 ; private static final int LINE_NUM = 10 ; public static void main ( String [ ] args) { BufferedImage captchaImage = generateCaptchaImage ( ) ; ImageIO . write ( captchaImage, "png" , System . out) ; } private static BufferedImage generateCaptchaImage ( ) { BufferedImage image = new BufferedImage ( WIDTH , HEIGHT , BufferedImage . TYPE_INT_RGB ) ; Graphics2D g = image. createGraphics ( ) ; Random random = new Random ( ) ; g. setColor ( Color . WHITE ) ; g. fillRect ( 0 , 0 , WIDTH , HEIGHT ) ; for ( int i = 0 ; i < CHAR_NUM ; i++ ) { g. setColor ( getRandomColor ( ) ) ; char c = getRandomChar ( ) ; g. drawString ( String . valueOf ( c) , 30 * i + 20 , 30 ) ; } for ( int i = 0 ; i < LINE_NUM ; i++ ) { g. setColor ( getRandomColor ( ) ) ; int x1 = random. nextInt ( WIDTH ) ; int y1 = random. nextInt ( HEIGHT ) ; int x2 = random. nextInt ( WIDTH ) ; int y2 = random. nextInt ( HEIGHT ) ; g. drawLine ( x1, y1, x2, y2) ; } g. dispose ( ) ; return image; } private static Color getRandomColor ( ) { Random random = new Random ( ) ; int r = random. nextInt ( 256 ) ; int g = random. nextInt ( 256 ) ; int b = random. nextInt ( 256 ) ; return new Color ( r, g, b) ; } private static char getRandomChar ( ) { Random random = new Random ( ) ; int index = random. nextInt ( CHAR_POOL . length ( ) ) ; return CHAR_POOL . charAt ( index) ; }
}