Method of Generating Verification Code Picture by java
- 2021-08-28 20:19:11
- OfStack
In this paper, we share the specific code of java to generate verification code pictures for your reference. The specific contents are as follows
Example 1:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;
public class RandomVerifyCode {
private static final String RANDOM_NUM = "23456789";
private static final String RANDOM_LETTER = "ABCDEFGHJKMNPQRSTUVWXYZ";
private static final String RANDOM_LETTER_SMALL = "abcdefghjkmnpqrstuvwxyz";
private static final String RANDOM_STRING = RANDOM_NUM + RANDOM_LETTER + RANDOM_LETTER_SMALL;
private int width = 95;// Picture width
private int height = 25;// Picture height
private int lineSize = 40;// Number of interference lines
private int stringNum = 4;// Randomly generate the number of characters
private Random random = new Random();
/**
* Get fonts
*/
private Font getFont() {
return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
}
/**
* Get color
*/
private Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc - 16);
int g = fc + random.nextInt(bc - fc - 14);
int b = fc + random.nextInt(bc - fc - 18);
return new Color(r, g, b);
}
/**
* Generate random pictures (BASE64 Format )
*/
public String getRandcode(HttpServletRequest request, StringBuffer imgBuffer) {
// BufferedImage Class has a buffer Image Class ,Image Class is a class for describing image information
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();// Produce Image Object's Graphics Object , You can perform various rendering operations on the image by changing the object
g.fillRect(0, 0, width, height);// Picture size
g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));// Font size
g.setColor(getRandColor(110, 133));// Font color
// Drawing interference line
for (int i = 0; i <= lineSize; i++) {
drowLine(g);
}
// Drawing random characters
String randomString = "";
for (int i = 1; i <= stringNum; i++) {
randomString = drowString(g, randomString, i);
}
g.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream();
String encode = null;
try {
// Output the pictures in memory to the client in flowing form
ImageIO.write(image, "JPEG", out);
encode = "data:image/jpeg;base64,"+Base64.encodeBase64String(out.toByteArray());
out.close();
} catch (Exception e) {
LogHelper.error(" Landing control "," Verification code generation "," Output the verification code picture generated in memory as BASE64 Format encoding failed! ");
}
imgBuffer.append(encode);
return randomString;
}
/**
* Drawing String
*/
private String drowString(Graphics g, String randomString, int i) {
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
.nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(RANDOM_STRING.length())));
randomString += rand;
g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(rand, 13 * i, 16);
return randomString;
}
/**
* Drawing interference line
*/
private void drowLine(Graphics g) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x, y, x + xl, y + yl);
}
/**
* Get random characters
*/
public String getRandomString(int num) {
return String.valueOf(RANDOM_STRING.charAt(num));
}
public static String randomString(int length){
return RandomStringUtils.random(length, RANDOM_STRING.toCharArray());
}
}
Example 2:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class CodeUtil {
private static int width = 90;// Object that defines a picture width 90
private static int height = 20;// Object that defines a picture height 20
private static int codeCount = 4;// Define the number of verification codes displayed on the picture
private static int xx = 15;
private static int fontHeight = 18;
private static int codeY = 16;
private static char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
public static Map<String,RenderedImage> codePicMap = new HashMap<>();
/**
* Generate 1 A map Set
* code For the generated verification code
* codePic For the generated verification code BufferedImage Object
*
* @return
*/
public static Map<String, Object> generateCodeAndPic() {
// Define an image buffer
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Graphics2D gd = buffImg.createGraphics();
// Graphics2D gd = (Graphics2D) buffImg.getGraphics();
Graphics gd = buffImg.getGraphics();
// Create 1 Random number generator classes
Random random = new Random();
// Fill the image in blue
// gd.setColor(Color.WHITE);
gd.setColor(new Color(232,240,254));
gd.fillRect(0, 0, width, height);
// Create a font. The size of the font should be determined according to the height of the picture.
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
// Set the font.
gd.setFont(font);
// Draw a border.
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);
// Random generation 40 Interference lines, so that the authentication code in the image is not easy to be detected by other programs.
gd.setColor(Color.BLACK);
for (int i = 0; i < 10; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
gd.drawLine(x, y, x + xl, y + yl);
}
// randomCode Used to save randomly generated verification codes for authentication after users log in.
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// Random generation codeCount The verification code of the number.
for (int i = 0; i < codeCount; i++) {
// Randomly generated verification code numbers are obtained.
String code = String.valueOf(codeSequence[random.nextInt(31)]);
// Random color components are generated to construct color values so that the color values of each number output will be different.
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// Draws the verification code into the image with randomly generated colors.
gd.setColor(new Color(red, green, blue));
gd.drawString(code, (i + 1) * xx, codeY);
// Will produce 4 Random numbers are combined in 1 Get up.
randomCode.append(code);
}
Map<String, Object> map = new HashMap<>();
// Store verification code
map.put("code", randomCode);
// Store the generated verification code BufferedImage Object
map.put("codePic", buffImg);
return map;
}
public static void main(String[] args) throws Exception {
// Create a file output stream object
OutputStream out = new FileOutputStream("D://img/" + System.currentTimeMillis() + ".jpg");
Map<String, Object> map = CodeUtil.generateCodeAndPic();
ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", out);
System.out.println(" The value of the verification code is: " + map.get("code"));
}
}