0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【 Java 】QRCode生成

Last updated at Posted at 2023-08-11

◾️ JavaでQRCodeを生成する方法

・使用ライブラリ
  ZXing
   ∟ core-3.5.1.jar
   ∟ javase-3.5.1.jar

※今回QRCode生成に至る詳しい処理については触れてません。
 お作法だと思って使ってます。
 オプションは複数あるらしいので、必要に応じて付与する。

Mainクラス
	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の生成に成功");
	}


◾️ 日本語対応版

デフォルトのCharasetが「ISO-8859-1」のため、文字列の指定に日本語を使うと文字化けしてしまいます。
EncodeHintTypeを使ってCharasetを指定してあげることで日本語でも文字化けせずQRCodeが生成できるようになります。

Mainクラス
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の生成に成功");
}

◾️ 参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?