package cn.demo1;
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[] strings = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n",
"o", "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->5->
//和自己画画一样的
/**
* 1、准备画板
* 2、准备笔
* 3、准备一些数据,随机在数组中取出四个数据(for循环)
* 4、将去除的数据画到画板上去
* 5、生成一个真正的是图片
*/
//定义一个图片的宽度
int w=210;
//定义高度
int h=170;
//图片的类型
int imageType=BufferedImage.TYPE_INT_RGB;
// 1、JDK中提供画板类
BufferedImage image=new BufferedImage(w,h,imageType);
//修改图片颜色 idea 图片默认黑色
//先获取画笔对象
Graphics g= image.getGraphics();
//设置画笔颜色
g.setColor(Color.pink);
//画一个填充矩形
g.fillRect(0,0,210,170);
//设置画笔颜色,不然和填充举证颜色一样,看不出来
g.setColor(Color.gray);
//设置字体
g.setFont(new Font("楷体",Font.TYPE1_FONT,45));
//使用Random随机产生一个数字
Random random=new Random();
int x=25,y=25;
//3、准备一些数据,随机在数组中取出四个数据(for循环)
for (int i = 0; i < 4; i++) {
//num 值是随机生成的
int num= random.nextInt(strings.length);
//每次循环取一个
String str= strings[num];
//每次获取一个数字画到图片上去
g.drawString(str,x,y);
x+= random.nextInt(65);
y+=random.nextInt(55);
}
g.setColor(Color.red);
for (int j = 0; j < 60; j++) {
//画干扰线
g.drawLine(random.nextInt(150)-100,random.nextInt(150)-70,
random.nextInt(150)+120, random.nextInt(150)+140);
}
//5.把image生成到本地的磁盘上
ImageIO.write(image,"jpg",new File("../aaa.jpg"));
}
}
代码来源于B站,侵权请联系删除