| | |
| | | import java.io.IOException; |
| | | import java.util.Hashtable; |
| | | |
| | | import static com.google.zxing.client.j2se.MatrixToImageConfig.BLACK; |
| | | import static com.google.zxing.client.j2se.MatrixToImageConfig.WHITE; |
| | | |
| | | /** |
| | | * @Author: dougang |
| | | * @Description: |
| | |
| | | |
| | | /** |
| | | * 生成二维码 |
| | | * |
| | | * @param contents |
| | | * @param width |
| | | * @param height |
| | | * @param level 0:M,1:L,2:H,3:Q |
| | | * @param level 0:M,1:L,2:H,3:Q |
| | | * @return |
| | | */ |
| | | public static String creatRrCode(String contents, int width, int height,int level) { |
| | | public static String creatRrCode(String contents, int width, int height, int level) { |
| | | String binary = null; |
| | | Hashtable hints = new Hashtable(); |
| | | hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); |
| | | switch (level){ |
| | | switch (level) { |
| | | case 0: |
| | | hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); |
| | | break; |
| | |
| | | contents, BarcodeFormat.QR_CODE, width, height, hints); |
| | | // 读取文件转换为字节数组 |
| | | ByteArrayOutputStream out = new ByteArrayOutputStream(); |
| | | |
| | | BufferedImage image = toBufferedImage(bitMatrix); |
| | | //切白边 |
| | | image = deleteWhite(bitMatrix); |
| | | |
| | | //转换成png格式的IO流 |
| | | ImageIO.write(image, "png", out); |
| | | byte[] bytes = out.toByteArray(); |
| | |
| | | image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); |
| | | } |
| | | } |
| | | |
| | | return image; |
| | | } |
| | | |
| | | /** |
| | | * 切白边 |
| | | * |
| | | * @param matrix |
| | | * @return |
| | | */ |
| | | private static BufferedImage deleteWhite(BitMatrix matrix) { |
| | | int[] rec = matrix.getEnclosingRectangle(); |
| | | int resWidth = rec[2] + 1; |
| | | int resHeight = rec[3] + 1; |
| | | |
| | | BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); |
| | | resMatrix.clear(); |
| | | for (int i = 0; i < resWidth; i++) { |
| | | for (int j = 0; j < resHeight; j++) { |
| | | if (matrix.get(i + rec[0], j + rec[1])) |
| | | resMatrix.set(i, j); |
| | | } |
| | | } |
| | | |
| | | int width = resMatrix.getWidth(); |
| | | int height = resMatrix.getHeight(); |
| | | BufferedImage image = new BufferedImage(width, height, |
| | | BufferedImage.TYPE_INT_RGB); |
| | | for (int x = 0; x < width; x++) { |
| | | for (int y = 0; y < height; y++) { |
| | | image.setRGB(x, y, resMatrix.get(x, y) ? BLACK : WHITE); |
| | | } |
| | | } |
| | | return image; |
| | | } |
| | | |
| | | public static void main(String[] args) { |
| | | String binary = QRCodeUtil.creatRrCode("https://baidu.com", 200,200,12); |
| | | String binary = QRCodeUtil.creatRrCode("http://192.168.2.146:8089/upload/saasmobile.html?hospitolId=1&departmentId=1&doctorId=1278159153159888898&childid=3001&diagnosticId=300101&puuid=dbd8b1c0-bdc5-11ea-b37d-1b33e9f3fd18", 200, 200, 2); |
| | | System.out.println(binary); |
| | | } |
| | | } |