资源描述:
《java随机产生验证码》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、packagecom.cstp.lottery.image;/***@authorsky9413@sina.com**创建图形验证码*/importjava.awt.Color;importjava.awt.Font;importjava.awt.Graphics2D;importjava.awt.image.BufferedImage;importjava.io.File;importjava.util.Date;importjava.util.LinkedList;importjava.util.Random;importjavax.imageio.ImageIO;i
2、mportjavax.servlet.http.HttpServletResponse;importcom.sun.image.codec.jpeg.JPEGCodec;importcom.sun.image.codec.jpeg.JPEGImageEncoder;publicclassRandomImage{publicStringsRand="";publicRandomImage(){}publicColorgetRandColor(intfc,intbc){//给定范围获得随机颜色Randomrandom=newRandom();if(fc>255)fc=255;
3、if(bc>255)bc=255;intr=fc+random.nextInt(bc-fc);intg=fc+random.nextInt(bc-fc);intb=fc+random.nextInt(bc-fc);returnnewColor(r,g,b);}/***通过文件创建图像*格式为jpg类型*/publicvoidcreatImage(StringfileName,Stringcontent){//在内存中创建图象intwidth=60,height=20;BufferedImageimage=newBufferedImage(width,height,Buff
4、eredImage.TYPE_INT_RGB);//获取图形上下文Graphics2Dg=image.createGraphics();//Graphicsg=image.getGraphics();//生成随机类Randomrandom=newRandom();//设定背景色g.setColor(getRandColor(200,250));g.fillRect(0,0,width,height);//设定字体g.setFont(newFont("TimesNewRoman",Font.PLAIN,18));g.setColor(Color.black);//黑色文字g
5、.drawString(content,10,15);g.dispose();try{Filef=newFile(fileName);if(!f.exists()){f.createNewFile();}else{Thread.sleep(200);f.delete();f.createNewFile();}ImageIO.write(image,"jpg",f);}catch(Exceptione){e.printStackTrace();}}/***创建图像*格式为jpg类型**@paramcontent-String图片输出内容*@returnjava.awt.im
6、age.BufferedImage*@since2005-7-19*/publicBufferedImagegetBufferedImage(Stringcontent){intwidth=60,height=20;returngetBufferedImage(content,width,height);}/***创建图像*格式为jpg类型**@paramcontent-String图片输出内容*@paramwidth-int图片宽度*@paramheight-int图片高度*@returnjava.awt.image.BufferedImage*@since2005-7
7、-19*/publicBufferedImagegetBufferedImage(Stringcontent,intwidth,intheight){//在内存中创建图象BufferedImageimage=newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//获取图形上下文Graphics2Dg=image.createGraphics();//Graphicsg=image.getGraphics();//生成随机类Randomrandom=newRando