import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
public class ImgDemo {
public static void main(String[] args) throws IOException {
// demo1();
// demo2();
demo3();
}
//验证码原理
private static void demo1() throws IOException {
BufferedImage bImg=new BufferedImage(60, 30, BufferedImage.TYPE_INT_RGB);
Graphics g=bImg.getGraphics();
g.drawString("hello", 0, 30);//版本二修正这一句
g.dispose();//相当于IO中的close()方法带自动flush();
ImageIO.write(bImg,"JPEG", new FileOutputStream("d:/myJavaWeb/b.jpg"));
}
//验证码版本二:随机数生成验证码
private static void demo2() throws IOException {
int width=64;
int height=40;
BufferedImage bImg=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g=bImg.getGraphics();
//背景
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
//字体颜色
g.setFont(new Font("aa", Font.BOLD,18));
//用随机数生成验证码:4个0~9以内的整数
Random r=new Random();
for(int i=1;i<5;i++){
int t=r.nextInt(10);//10以内的随机整数
int y=10+r.nextInt(20);//上下位置:10~30
Color c=new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
g.setColor(c);
g.drawString(""+t, i*16, y);
}
//画干扰线
for(int i=1;i<5;i++){
Color c=new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
g.setColor(c);
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
//把图形刷到bImg对象中
g.dispose();//相当于IO中的close()方法带自动flush();
ImageIO.write(bImg,"JPEG", new FileOutputStream("d:/myJavaWeb/b.jpg"));
}
//让验证码进行缩和旋转
private static void demo3() throws IOException {
int width=128,w=width/4;
int height=60;
BufferedImage bImg=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g=bImg.getGraphics();
Graphics2D g2D=(Graphics2D) g;
//背景
g2D.setColor(Color.white);
g2D.fillRect(0, 0, width, height);
//字体颜色
g2D.setFont(new Font("aa", Font.BOLD,18));
//用随机数生成验证码:4个0~9以内的整数
Random r=new Random();
for(int i=1;i<=4;i++){
int t=r.nextInt(10);//10以内的随机整数
int y=30;
Color c=new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
g2D.setColor(c);
//旋转和缩放
AffineTransform tx=new AffineTransform();
tx.rotate(r.nextDouble(), i*w/2, y);
tx.scale(0.6+r.nextDouble(), 0.6+r.nextDouble());
g2D.setTransform(tx);
g2D.drawString(""+t, i*w/2, y);
}
//画干扰线
for(int i=1;i<8;i++){
Color c=new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
g2D.setColor(c);
g2D.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
//把图形刷到bImg对象中
g2D.dispose();//相当于IO中的close()方法带自动flush();
ImageIO.write(bImg,"JPEG", new FileOutputStream("d:/myJavaWeb/b.jpg"));
}
}
java--验证码原理
最新推荐文章于 2023-10-30 20:12:12 发布