public static void main(String[] args) throws Exception{ int n = 7;//版本,亦是二维码大小 Qrcode qrcode = new Qrcode(); qrcode.setQrcodeErrorCorrect('H');//纠错等级(分为L、M、H三个等级) qrcode.setQrcodeEncodeMode('B');//N代表数字,A代表a-Z,B代表其它字符 qrcode.setQrcodeVersion(n);//版本 //生成二维码中要存储的信息(这里使用随机混合生成8位带数字和字母的编码) String qrCode = "";//随机混合生成8位带数字和字母的编码 Random random = new Random(); for (int i = 0; i < 8; i++){ String str = random.nextInt(2) % 2 == 0 ? "num" : "char"; if ("char".equalsIgnoreCase(str)){ // 产生字母 int nextInt = random.nextInt(2) % 2 == 0 ? 65 : 97; qrCode += (char)(nextInt + random.nextInt(26)); }else if ("num".equalsIgnoreCase(str)){ // 产生数字 qrCode += String.valueOf(random.nextInt(10)); } } //设置一下二维码的像素 int width = 67+12*(n-1); int height = 67+12*(n-1); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //绘图 Graphics2D gs = bufferedImage.createGraphics(); gs.setBackground(Color.WHITE); gs.setColor(Color.BLACK); gs.clearRect(0, 0, width, height);//清除下画板内容 //设置下偏移量,如果不加偏移量,有时会导致出错。 int pixoff = 2; byte[] d = qrCode.getBytes("gb2312"); if(d.length > 0 && d.length <120){ boolean[][] s = qrcode.calQrcode(d); for(int i=0;i<s.length;i++){ for(int j=0;j<s.length;j++){ if(s[j][i]){ gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3); } } } } gs.dispose(); bufferedImage.flush(); ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流 ImageIO.write(bufferedImage, "png", baos);//写入流中 byte[] bytes = baos.toByteArray();//转换成字节 BASE64Encoder encoder = new BASE64Encoder(); String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串 png_base64 = png_base64.replaceAll(" ", "").replaceAll(" ", "");//删除 ImageIO.write(bufferedImage, "png", new File("D:/qrcode1.png")); System.out.println("结束"); }
需要的两个jar包:
Qrcode-C.jar
qrcode-R.jar