LoginSignup
1
0

More than 1 year has passed since last update.

[小ネタ]メールにQRコードを貼っつけたい

Last updated at Posted at 2021-12-22

この記事は ZOZO #3 Advent Calendar 2021 23日目の記事になります。

今どきはバーコードではなく、QRコードなんですよね。ということで、メールにQRコードを貼り付けたい!

javaでの例になります。javaですと、ZXingというツールが使えます。QRコード以外にもバーコードの生成も可能のようです。

QRコードの生成方法は以下の通り。画像を生成してS3に保存する例になります。


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 com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;

// 引数にQRコードの元となる文字列を渡しています。
public void createQRCode(String qrcode, String s3BucketName){
    BarcodeFormat format = BarcodeFormat.QR_CODE;
    int width = 82;
    int height = 82;

    Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
       // エラー訂正レベル L→M→Q→Hの順にQRコード内の密度が上がって複雑になる
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
      QRCodeWriter writer = new QRCodeWriter();
      BitMatrix bitMatrix = writer.encode(qrcode, format, width, height, hints);
      BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      ImageIO.write(image, "png", stream);
      stream.flush();
      byte[] imageInByte = stream.toByteArray();
      stream.close();

      ObjectMetadata metadata = new ObjectMetadata();
      metadata.setContentType("image/png");
      PutObjectRequest request =
          new PutObjectRequest(s3BucketName, "qrcode-images/qrCode.png"),
              new ByteArrayInputStream(imageInByte), metadata);
      s3Client.putObject(request);

    } catch (IOException | WriterException e) {
      throw new RuntimeException(e);
    }
}

ポイントとしては、QRコードをBase64での生成も可能で、圧倒的にBase64を使うのが楽なのですが、メーラーのブラウザではBase64がほとんど対応しておらず、メールを受信しても閲覧できない。そのため今回はS3に保存してそこを参照するようにしています。

以上小ネタでした。

※ちなみにQRコードはデンソーウェーブ社の登録商標になります。

明日は、@taquaki-satwoさんの記事になります!

1
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
1
0