生成图片验证码工具类
程序员文章站
2022-05-19 19:17:10
...
首先绘制图片依赖 commons-codec-1.10.jar包,我已上传
package PicCheckCode;
import org.apache.commons.codec.binary.Base64;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
public class CheckPicCode {
private static String picCode;
public static String getPicCode() {
return picCode;
}
public static void setPicCode(String picCode) {
CheckPicCode.picCode = picCode;
}
public static String getCheckCode(){
//验证码中的字符由数字和大小写字母组成
String code = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
Random r = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
sb.append(code.charAt(r.nextInt(code.length())));
}
return sb.toString();
}
public static BufferedImage showPic() throws IOException {
String code=getCheckCode();
setPicCode(code);
int width=80;
int height=30;
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,width,height);
Random r=new Random();
for (int i=0;i<3;i++){
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.drawLine(r.nextInt(80),r.nextInt(30),r.nextInt(80),r.nextInt(80));
}
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.setFont(new Font("黑体",Font.BOLD,24));
g.drawString(code,15,20);
g.dispose();//图像生效
return image;
}
public static String encodeBase64ImgCode() throws IOException{
BufferedImage codeImg=showPic();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(codeImg, "JPEG", out);
byte[] b = out.toByteArray();
String imgString = Base64.encodeBase64String(b);
return "data:image/JPEG;base64," + imgString;
}
public static void main(String[] args) throws IOException {
String base64PicCodeImage = encodeBase64ImgCode();
String checkCode = getPicCode();
System.out.println("验证码==》"+checkCode);
System.out.println("base64图片字符串==》"+base64PicCodeImage);
}
}
执行main方法,打印结果如下:
新建HTML网页
<html>
<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Mc1gfFq2lvLvw/a26b5pnljjXIGWJjAGTx1NaWq2Go+E9f1TxVY/ZJdNmiBubNpTCS3AyONpbPOTydzADJydowh7OLtq7/ffQ7qVDD/AFek2lzyUrX6vmSV/le19DU8KeLG16W8sL21W01OxbZNEsgYMRwxXvgMCD1AyvJzWxLd6gmtQWsemeZYOhaS989R5bfN8uzqei8/7XtXIfDSwlnj1LxJdxxLNqc7GMKo+VQxLYOSQCxIwf7gPPFWNTvryP4t6NZJdTraSWbM8AkIRjiXkr0J4H5Cs504+0ko9F+hz18NT+tVKdJK0Yt9bJpa216Pa521FFFcx5IUVgar4v0/SPENlotxDctc3nl+W0aqUG9ygySwPUelaN7f/Z7q1so1zcXe8RMw+RdoBJbnPToB16ZHWh6CujF8T6KNX1nRbiO4YXGnzeesAiLB8sp+Zs4QfIeTnPOASMHQ1Hw7Ya3pz2+qRJPI6kfaAgV05yCh6gDsOffOTnShgW2hYKWZjlnduWdvU/p7AAAYAAqYDAwKrnlprtsb/WKtoq/w7eWt/wAzi9L8AfZruwn1TWbnUV07b9iiK+WkWCTzySeduOR90A5AAGx4o8PSeJbKCxN+1raCUSXCxplpQOi5zgDvyDyFPbncoqnWm5KTeqNJY2vKoqrlqttFp8rWGRRRwRJFEixxooVEQYCgcAAdhWHd+GvtXjSx8Rfa9v2WAw/Z/LzuyHGd2ePv+nat+ipjJx2MadadNtxe6afo9woooqTM/9k=">
</html>
打开HTML显示如下:
上一篇: 基于慕课网-----Java验证码的实现