【Java】生成二维码

◾️ 如何使用Java生成QRCode

・使用库
  ZXing
   ∟ core-3.5.1.jar
   ∟ javase-3.5.1.jar
※对于本次QR Code生成的详细处理方法不做详述。
我认为这是一种常规做法,所以在使用中。
听说有多个选项可供选择,根据需要进行添加。
	public static void main(String[] args) {
		// QR読み取り時に表示する文字列
		String content = "https://qiita.com/devdia";
		// 画像サイズ(ピクセル)
		int width = 200;
		int height = 200;
		
		try {
			QRCodeWriter qw = new QRCodeWriter();
			BitMatrix bm = qw.encode(content, BarcodeFormat.QR_CODE, width, height);
			BufferedImage img = MatrixToImageWriter.toBufferedImage(bm);
			ImageIO.write(img, "png", new File("src/images/outputQRCode.png"));
		} catch (WriterException | IOException e) {
			System.err.println("QRCode生成時に例外発生" + e);
		}
		System.out.println("QRCodeの生成に成功");
	}


◾️ 日本语支持版本

由于默认的字符集是”ISO-8859-1″,当使用日语进行字符串指定时会出现乱码。通过使用EncodeHintType来指定字符集,即可在日语中不再出现乱码,生成QRCode。

public static void main(String[] args) {
    // QR読み取り時に表示する文字列
    String content = "日本語データ";
    // 画像サイズ(ピクセル)
    int width = 200;
    int height = 200;
    // HashMapより、EnumMapを使うことで実行効率が上がるらしい...
    Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
    // Charasetを"UTF-8"に指定
    hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8);
    
    try {
        QRCodeWriter qw = new QRCodeWriter();
        // 引数にQRCode生成時のヒントとなる情報を渡す
        BitMatrix bm = qw.encode(content, BarcodeFormat.QR_CODE, width, height,hints);
        BufferedImage img = MatrixToImageWriter.toBufferedImage(bm);
        ImageIO.write(img, "png", new File("src/images/outputQRCode.png"));
    } catch (WriterException | IOException e) {
        System.err.println("QRCode生成時に例外発生" + e);
    }
    System.out.println("QRCodeの生成に成功");
}

◾️ 参考资料

bannerAds