使用java代码生成图片验证码

时间:2022-11-04 08:34:41

本文使用java代码生成简单的图片,可以用来作为图片验证码,代码如下:

package cn.itcast;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

public class Demo {
public static void main(String[] args) throws Exception, Exception {
BufferedImage bi = new BufferedImage(150,70,BufferedImage.TYPE_3BYTE_BGR);
//得到图片缓冲区

Graphics2D g2 = (Graphics2D)bi.getGraphics();
//得到绘制环境

g2.setColor(Color.WHITE);
//设置颜色

g2.fillRect(0, 0, 150, 70);
//填充整张图片
g2.setColor(Color.RED);
g2.drawRect(0, 0, 150-1, 70-1);

g2.setFont(new Font("宋体",Font.BOLD,18));

g2.setColor(Color.BLACK);

g2.drawString("Hello word", 3, 30);
//图片上也字符串

ImageIO.write(bi, "JPEG", new FileOutputStream("E:/a.jpg"));

}

}