图片验证码的Java实现方式

      在网站登录或者验证的时候,为了防止有人使用程序不断发送登录,注册信息等,要求发送者输入图片上的信息,以提高安全性。

实现代码如下:

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();
		}
	}

}

图片验证码的执行结果:

                                         

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值