java生成二维码工具类

jar包

		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.0.0</version>
		</dependency>

		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.3.0</version>
		</dependency>
/**
	 * 生成二维码
	 * @param content
	 * @param format
	 * @param outputPath
	 * @return
	 * @throws Exception
	 */
	public static File createQrCodeImage(String content, String format, String outputPath) throws Exception {
		// String text = "老宁是狗,汪汪汪"; // 二维码内容
		int width = 300; // 二维码图片宽度
		int height = 300; // 二维码图片高度
		// String format = "png";// 二维码的图片格式

		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

		BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		deleteWhite(bitMatrix);
		// 生成二维码
		File outputFile = new File(outputPath);
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		return outputFile;
	}

	public static File createQrCodePicture(String content, String outputPath) throws Exception {
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();

		hints.put(EncodeHintType.MARGIN, 0);
		BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, 256, 256, hints);

		// 1.1去白边

		int[] rec = bitMatrix.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 (bitMatrix.get(i + rec[0], j + rec[1])) {

					resMatrix.set(i, j);

				}

			}

		}

		// 2

		int width = resMatrix.getWidth();

		int height = resMatrix.getHeight();

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

		for (int x = 0; x < width; x++) {

			for (int y = 0; y < height; y++) {

				image.setRGB(x, y, resMatrix.get(x, y) == true ?

						Color.BLACK.getRGB() : Color.WHITE.getRGB());

			}

		}

		// 3
		File file = new File(outputPath);
		ImageIO.write(image, "png", file);
		return file;
	}

	/**
	* 删除白边
	* */
	private static BitMatrix 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);
				}
			}
		}
		return resMatrix;
	}
	
/* * @param width 二维码的宽
     * @param height 二维码的高
     * @return BitMatrix对象
     * */
	public static BitMatrix createCode(String content,int width,int height) throws IOException {

		//其他参数,如字符集编码
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		//容错级别为H
		hints.put(EncodeHintType.ERROR_CORRECTION , ErrorCorrectionLevel.H);
		//白边的宽度,可取0~4
		hints.put(EncodeHintType.MARGIN , 0);

		BitMatrix bitMatrix = null;
		try {
			//生成矩阵,因为我的业务场景传来的是编码之后的URL,所以先解码
			bitMatrix = new MultiFormatWriter().encode(content,
					BarcodeFormat.QR_CODE, width, height, hints);
			bitMatrix = deleteWhite(bitMatrix);
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return bitMatrix;
	}
	/**
	 * 生成base64二维码图片
	 *
	 * @param content
	 * @return
	 */
	public static String createQrCodeImg(String content) {
		try {
			QRCodeWriter qrCodeWriter = new QRCodeWriter();
			BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 600, 600);

			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);

			Base64.Encoder encoder = Base64.getEncoder();

			return "data:image/jpeg;base64,"
					+ encoder.encodeToString(outputStream.toByteArray()).replaceAll("\r|\n", "");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	//以流的形式输出
	@Override
    public void getProjectMeetingQRCode(Integer id, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            // 设置响应流信息
            response.setContentType("image/png");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            outputStream = response.getOutputStream();
            //二维码的宽高
            int width = 200;
            int height = 200;

            //获取一个二维码图片
            BitMatrix bitMatrix = QrCodeUtil.createCode(content, width, height);
            //以流的形式输出到前端
            MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不会敲代码阿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值