package cn.com.lx;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import org.junit.Test;
public class Image {
private int w=70;
private int h=35;
private Random r=new Random();
//1.RGB颜色
private Color col=new Color(255, 255, 255);//三个值要在这个区间内,怎么变成了都是255不就是一个颜色了么?
public Color setC(){
int red=r.nextInt(155);
int green=r.nextInt(155);
int blue=r.nextInt(155);
Color color=new Color(red,green,blue);
return color;
}
//2.字体
public Font setF(){
//字体形式,大小,楷书等
int size=r.nextInt(4)+25;
int style=r.nextInt(4);
String [] string ={"宋体","楷体"};
int index=r.nextInt(string.length);
String name=string[index];
Font font=new Font(name,style,size);
return font;
}
//3.字符
public char setCh(){
String chars="1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBVNM";
int index=r.nextInt(chars.length());
char ch=chars.charAt(index);
return ch;
}
//4.干扰线
public void DrawLine(BufferedImage bff){
Graphics2D gh=(Graphics2D) bff.getGraphics();
for (int i = 0; i <3; i++) {
//1.三条干扰线
int x1=r.nextInt(w);
int x2=r.nextInt(w);
int y1=r.nextInt(h);
int y2=r.nextInt(h);
gh.setStroke(new BasicStroke(1.5F));
gh.setColor(Color.blue);
gh.drawLine(x1, y1, x2, y2);
}
}
public BufferedImage bff(){
//1.缓存区
BufferedImage img=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//2.设置颜色以及前期准备
Graphics2D gh2=(Graphics2D) img.getGraphics();
gh2.setColor(col);
gh2.fillRect(0, 0, w, h);
return img;
}
//5.开始绘制
@Test
public void draw() throws FileNotFoundException, IOException{
BufferedImage img=bff();
Graphics2D gh2=(Graphics2D) img.getGraphics();
//StringBuilder sb=new StringBuilder();
//3.图形绘制
for (int i = 0; i <4; i++) {
gh2.setFont(setF());
gh2.setColor(setC());
String c=setCh()+"";
// sb.append(c);
float x=i*1.0F*w/4;
gh2.drawString(c, x, h-5);
}
//4.添加干扰线
DrawLine(img);
ImageIO.write(img, "JPEG", new FileOutputStream("D:/g.jpg"));
}
}
java代码完成验证码的生成
猜你喜欢
转载自blog.csdn.net/qq_37591637/article/details/82781167
今日推荐
周排行