package com.yunhe.dayzizhulianxi;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
/**
*
* @author hou
* @date: 2021年11月28日 下午4:03:36
*图片验证码的而开发
*/
public class ImageTest {
//定义一个数组
static String[] strs = {"a","b","c","d","e","f","g","h","i","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) {
/**
* 1.画板 纸
* 2.准备画笔
* 3.准备一些数据,随机从中获取四个
* 4.通过画笔把获取的数据写到画板上
* 5.生成一张图片
*/
//定义图片的高度
int h = 50;
//定义图片的宽度
int w = 150;
//图片的类型 图片的组成方式 RGB red green blue三原色
//int imageType = BufferedImage.TYPE_INT_RGB;
//int imageType = 1;
//1.画板 纸 JDK中提供画板类
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//先获取画笔的对象
Graphics g = image.getGraphics();
//给画笔设置颜色
g.setColor(Color.yellow);
//画矩形进行填充(将原来的图片进行覆盖)
g.fillRect(0, 0, w, h);
//定义x轴,y轴
int x=30;
int y=30;
//给画笔再次设置颜色
g.setColor(Color.red);
//设置字体
g.setFont(new Font("楷体",Font.PLAIN,25));
//准备数据,从中选取四个数据
Random random = new Random();
for(int i=0;i<4;i++){
//在字符串数组中拿到四个索引
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(50);;
// int x2=random.nextInt(30)+120;
// int y2=random.nextInt(50);
// g.drawLine(x1, y1, x2, y2);
// }
int x1=20;
int y1=25;
int x2=130;
int y2=35;
//画干扰线
g.drawLine(x1, y1, x2, y2);
//把生成的图片放在磁盘上
try {
ImageIO.write(image, "jpg", new File("F:\\yunheshuju\\image.jpg"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
生成验证码图片
最新推荐文章于 2023-12-05 10:11:00 发布