Java快速生成二维码--ZXing 包

jar包 Zxing 3.0.jar

public class Qrcode {
	

		private static final String QRCODE_DEFAULT_CHARSET = "GBK";//编码格式

		public static final int QRCODE_DEFAULT_HEIGHT = 152;// 二维码宽度

		public static final int QRCODE_DEFAULT_WIDTH = 152;// 二维码高度

		private static final int BLACK = 0xFF000000;

		private static final int WHITE = 0xFFFFFFFF;

		public static void main(String[] args) throws IOException {
			String data = "手机号:1111111111111\r\n微信号:2222222222222222";// 二维码内容
			BufferedImage image1 = createQRCode(data,152, 152);
			ImageIO.write(image1, "jpg", new File("D:/erweima.jpg"));
		}
		
		/**
		 * 创建具有指定字符集的QR码
		 * 
		 * @return
		 */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		public static BufferedImage createQRCode(String data, String charset, int width, int height) {
			Map hint = new HashMap();
			hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
			hint.put(EncodeHintType.CHARACTER_SET, charset);
			hint.put(EncodeHintType.MARGIN, 0);// 设置边框
			return createQRCode(data, charset, hint, width, height);
		}
		

		/**
		 * 创建默认设置二维码
		 * 
		 * @param data
		 * @param width
		 * @param height
		 * @return
		 */
		public static BufferedImage createQRCode(String data, int width, int height) {
			return createQRCode(data, QRCODE_DEFAULT_CHARSET, width, height);
		}

		public static BufferedImage createQRCode(String data, String charset, Map<EncodeHintType, ?> hint, int width,
				int height) {
			BitMatrix matrix;
			try {
				matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE,
						width, height, hint);
				return toBufferedImage(matrix);
			} catch (WriterException e) {
				throw new RuntimeException(e.getMessage(), e);
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(), e);
			}
		}

		public static BufferedImage toBufferedImage(BitMatrix matrix) {
			int width = matrix.getWidth();
			int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
				}
			}
			return image;
		}

	}

下载地址 :Zxing3.0.jar

猜你喜欢

转载自blog.csdn.net/hqbootstrap1/article/details/81131255