public static void main(String[] args) { try { tiaoxing("6923790798701"); } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void tiaoxing(String contents) throws WriterException, IOException { //设置编码格式 Map<EncodeHintType, Object> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //设置条形码的号码、编码方式、小及大编码格式BarcpdeFormat.EAN_13为条形码格式 var bm = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, 300, 200, hints); //创建画板 var i = MatrixToImageWriter.toBufferedImage(bm); ImageIO.write(i, "png", new File("img/tiaoxing.png")); BufferedImage j = new BufferedImage(400, 300, 2); var m = j.createGraphics(); m.setColor(Color.WHITE); m.fillRect(0, 0, j.getWidth(), j.getHeight()); m.drawImage(i, (j.getWidth() - i.getWidth()) / 2, (j.getHeight() - i.getHeight()) / 2, null); String text = contents; m.setColor(Color.BLACK); //字体格式 Font font = new Font("微软雅黑", Font.BOLD, 33); //字体 var fm = m.getFontMetrics(font); var tw = fm.stringWidth(text); font = font.deriveFont(20f); m.setFont(font); m.drawString(text, 120, j.getHeight() - fm.getDescent() - 10); m.dispose(); ImageIO.write(j, "png", new File("img/2.png")); }
二维码原理(将字符串信息通过一规则转换为图像)