/** * @Author: Ember * @Date: 2021/3/11 19:32 * @Description: 二维码生成工具类 */ public class QRCodeUtils { /** * 种子 */ private static int SEED = 255; /** * 线性同余发生器生成的随机数不大于M */ private static final int M = 10; /** * 生成随机数的最大最小值 */ private static final int MAX = 9; private static final int MIN = 0; private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private static final int DEFAULT_HEIGHT = 300; private static final int DEFAULT_WEIGHT = 300; private static final String CHAR_SET = "utf-8"; private static final int MARGIN = 1; /** * 使用线性同余生成随机数 * @return */ private static int createOneRandom(int seed){ Random random = new Random(); //线性同余器需要的系数 int a = random.nextInt(1024); int b = random.nextInt(1024); int result = (a * seed + b) % M; return result; } /** * 使用线性同余器生成 * @param seed * @return */ private static int createRandom(int seed){ int result = MIN + seed % (MAX - MIN + 1); return result; } /** * 生成16位随机数组合 * @return */ public static String createQRCode(){ StringBuffer buffer = new StringBuffer(); buffer.append("QR"); int size = 15; int seed = SEED; for (int i = 0; i buffer.append(createOneRandom(seed)); //重置seed seed = createOneRandom(seed); } return buffer.toString(); } /** * 生成二维码图片 * @param text */ public static void encode(String text){ Map params = new HashMap<>(2); params.put(EncodeHintType.CHARACTER_SET,CHAR_SET); params.put(EncodeHintType.MARGIN,MARGIN); try { BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE,DEFAULT_WEIGHT,DEFAULT_HEIGHT,params); int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //对二维码进行上色 //嵌套for索引坐标 for (int i = 0; i } ImageIO.write(image,"JPG",new File("D:\\"+text+".jpg")); } catch (WriterException | IOException e) { e.printStackTrace(); } }