资料来源:https://www.bilibili.com/video/BV1Aq4y1W79E?p=4&spm_id_from=pageDriver
package cn.tx.imageCode.demo;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.Random;public class ImageCode {static String [] strs = {"a", "b", "c", "d", "e", "f", "g", "h", "j", "k","m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "2","3", "4", "5", "6", "7", "8", "9"};public static void main(String[] args) throws IOException {// 大的需求:通过Java代码的方式生成图片(图片上含有字母或数字或者干扰线)// 如:画画一样/*** 1. 画板 纸* 2. 准备画笔* 3. 准备一条数据,随机从数组中获取4个* 4. 通过画笔把获取到的数据画到画板上* 5. 生成一张真正的图片*/// 定义图片的宽度int w = 150;// 定义图片高度int h = 50;// 定义图片的类型 图片的组成方式 RGB由red、green、blue三原色组成int imageType = BufferedImage.TYPE_INT_RGB;// 1. 画板 纸 JDK中提供画板类 ctrl + p快捷键查看方法的参数BufferedImage image = new BufferedImage(w, h , imageType);// 修改图片的颜色。图片默认的颜色是黑色的// 2. 准备画笔。获取画笔对象Graphics g = image.getGraphics();// 先给画笔设置颜色g.setColor(Color.yellow);// 画填充矩形g.fillRect(0,0, w, h);// 全部填充// 再重写设置颜色(设置的是字体的颜色)g.setColor(Color.red);// 设置字体g.setFont(new Font("楷体", Font.PLAIN, 25));Random random = new Random();int x = 25;int y = 25;// 3. 准备一条数据,随机从数组中获取4个for (int i = 0; i < 4; i++) {// 取strs长度中一个随机数字int num = random.nextInt(strs.length);String str = strs[num];// 每获取一个字符串,画上去g.drawString(str, x, y);// 每画一次,把X的值变大,不然每次画的值重叠x += 25;}g.setColor(Color.green);for (int i = 0; i < 10; i++) {int x1 = random.nextInt(30);int y1 = random.nextInt(30);int x2 = random.nextInt(30) + 120;int y2 = random.nextInt(50);// 画一点干扰线g.drawLine(x1, y1, x2, y2);}// 5. 生成一张真正的图片。把image生成到本地的磁盘上ImageIO.write(image, "jpg", new File("D:\\aa.jpg"));}}
