
はじめに
事前に以下のライブラリを用意します。
- ZXing
- jarファイルをMaven Repositoryから取得すると使いやすいです。
- http://mvnrepository.com/artifact/com.google.zxing/core/3.2.1
- ※”Download ( JAR ) “のリンクからダウンロード
実装例
サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。
結果だけを確認したい場合は、この記事の一番下のリンク先で使えるようにしてありますのでご覧ください。
QRCodeEncoder.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; import javax.imageio.ImageIO; /** * * @author tool-taro.com */ public class QRCodeEncoder { public static void main(String[] args) throws WriterException, IOException { //QRコード生成したい文字列 String source = "タロウ" ; //QRコード生成時のエンコーディング String encoding = "UTF-8" ; //サイズ(ピクセル) int size = 100 ; //画像ファイルの保存先 String filePath = "qr_code.png" ; //生成処理 ConcurrentHashMap hints = new ConcurrentHashMap(); //エラー訂正レベル指定 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //エンコーディング指定 hints.put(EncodeHintType.CHARACTER_SET, encoding); //マージン指定 hints.put(EncodeHintType.MARGIN, 0 ); QRCodeWriter writer = new QRCodeWriter(); BitMatrix bitMatrix = writer.encode(source, BarcodeFormat.QR_CODE, size, size, hints); BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix); //ファイルへの保存処理 ImageIO.write(image, "png" , new File(filePath)); } } |
動作確認
1 2 | $ javac QRCodeEncoder.java $ java QRCodeEncoder |
以下のような画像が出力されているはずです。
環境
- 開発
- Windows 10 Pro
- JDK 1.8.0_74
- NetBeans IDE 8.1
- 動作検証
- CentOS Linux release 7.2
- JDK 1.8.0_74
上記の実装をベースにWebツールも公開しています。
QRコード生成(QR Code Generator)|Web便利ツール@ツールタロウ