LoginSignup
7

More than 5 years have passed since last update.

posted at

updated at

Google Chart API を使用したQRコード生成

そもそも Google Chart は何者なのだろうか?

 簡単にまとめれば、無料で使えるグラフィックツール。

 棒グラフ、折れ線グラフなどの基本的なグラフに加えて、地理グラフのようなリッチなコンテンツも提供されており、パラメータを指定するだけで簡単に作成できる。

 詳しくは下記公式サイト参照
公式サイト

Google Chart API の Image APIを使用してQRコードを生成する

 現在非推奨のため、サービスが停止される可能性もあり、そのあたりは注意。

基本のフレーム

 http://chart.apis.google.com/chart?

 上記Root URIにパラメータを指定していく

セットするもの

パラメータ        必須/オプション           内容 
cht 必須 Chart Typeを指定する。QRコードの場合はcht=qrと指定。
chs 必須 Chart Sizeを指定する。幅x高さ。
chl 必須 エンコードするデータを指定する。
choe オプション Chart Output Encodingを指定する。日本語対応の場合はShift_JISを指定。
chld オプション エラー訂正のレベルを指定。

公式リファレンス

試しにQiitaに飛ばすQRコードを生成してみる

プログラム内での動的な生成

chl= に値を渡すように組めばできる

jQueryによるサンプルコード

qiita.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>QRコード生成</title>
    </head>
    <body>
        <h1>QRコード生成</h1>
        <p>
            <!-- データ入力 -->
            <input type="text" id="msg">

            <!-- エンコード処理イベントボタン -->
            <input type="button" id="button" value="変換">
        </p>
        <div id="barCode"></div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        </script>
        <script>
           $(function(){
            // 変換ボタン押下時の処理
            $('#button').click(function(){
                // データ取得 日本語対応のためencodeURIComponentで処理
                var msg = encodeURIComponent($('#msg').val());
                // QRコードを置くためのimgタグ生成
                var img = $('<img>').attr('src','https://chart.apis.google.com/chart?cht=qr&chs=150x150&choe=Shift_JIS&chl='+msg);
                // 生成したimgタグの挿入
                $('#barCode').html(img);
             });
           });
        </script>
    </body>
</html>

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
What you can do with signing up
7