在网站登录或者验证的时候,为了防止有人使用程序不断发送登录,注册信息等,要求发送者输入图片上的信息,以提高安全性。
实现代码如下:
package com.uestc.test;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
public class ImageCreator {
private static String str="颞部发呢热佛如警女人飞年份恩赐";
//产生随机颜色
public static Color getRandomColor(){
Random random=new Random();
return new Color(Math.abs(random.nextInt(255)),Math.abs(random.nextInt(255)),Math.abs(random.nextInt(255)));
}
public static void main(String[] args) throws NoSuchMethodException,
SecurityException {
int width=200;
int height=100;
Random random=new Random();
BufferedImage im=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D grapgic=(Graphics2D)im.getGraphics();
//设置图片背景颜色
grapgic.setColor(Color.white);
grapgic.fillRect(0, 0, width, height);
//设定文字大小
Font font=new Font("华文楷书",Font.BOLD,18);
grapgic.setFont(font);
int num=Math.abs(random.nextInt(4));
//产生num个随机数字
for(int i=0;i<num;i++){
grapgic.setColor(getRandomColor());
grapgic.drawString(String.valueOf(random.nextInt()%10),i*width/4+10, height/2);
}
//产生4-num个随机汉字
for(int j=num;j<4;j++){
grapgic.setColor(getRandomColor());
grapgic.drawString(String.valueOf(str.charAt(Math.abs(random.nextInt(str.length())))),j*width/4+10, height/2);
}
//获取字体的大小
FontMetrics metrics=grapgic.getFontMetrics();
grapgic.drawLine(0, height/2-metrics.getHeight()/4, width, height/2-metrics.getHeight()/2);
//释放此图形的上下文并释放它所使用的所有系统资源
grapgic.dispose();
File file=new File("d:\\example.png");
try {
ImageIO.write(im, "png", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
图片验证码的执行结果: