How To Add QR Codes To Your Blog

by on February 19, 2011

If you haven't noticed them yet, QR codes are popping up everywhere. They're in advertisements, business cards, web sites, warehouse inventory, adhesive stickers, and even on t-shirts. To the left is the one for our site's home page.

They've been used in Japan for several years. The coding system was developed in 1994 by Japanese corporation Denso-Wave for automotive parts tracking.

They're similar to bar codes which are linear one-dimensional codes that can only hold up to 20 numerical digits. QR, or Quick Response, codes on the other hand are two-dimensional and can store about 4K of alphanumeric characters.

Actual capacity depends on the content type … they can incorporate numerical, alphanumerical, binary, or even Kanji/Kana Japanese letters as data. There are also 4 error correction levels (redundancy backup) and 40 symbol version settings which reduce the maximum capacity of final content. Typical usage is 300 characters or less.

In addition to hand-held scanners, they can be read by mobile phones with cameras and QR Code Reader software (usually a free app). They're also known as mobile tagging. Some claim that this technology is central to the future of mobile Internet usage. Who knows what innovations new technologies will introduce for using these matrix codes.

Here are a few sites that let you build the image code online and then download it.

Here's a site that DECODES a QR image to verify the data:
http://zxing.org/w/decode.jspx.

And, here are a few sites that let you download a QR Code reader for your mobile device.

So … let's construct a shortcode to create QR codes for each page of our blog. Ours will use a Google service to generate the graphic for any URL. This is our first gizmo … shortcodes that pull content from external sites and/or services.

Plus, we'll kick it up a notch by offering a color option not available from Google. Keep in mind though that the color should be dark (for performance). Also, you can actually utilize our shortcode for any textual content … by setting the URL and error correction level accordingly.

Their API is explained here.

Update 2011-05-07:

A more robust version of these functions is now available as an official WordPress plugin. Visit Plugin: WCS QR Code Generator for the download and usage details.

QR Code for WordPress

Here's the basic code for this page using our shortcode:

And, here it is enlarged and blue:

If you want to use the default options, no attributes are required. This is the code:
[gizmo_qr_code_image]

Each attribute is optional. See the code for the default values. The full syntax is:
[gizmo_qr_code_image size=SIZE color=HEX_VALUE url=FULL_URL ecl='L|4']

Refer here for details on the error correction level attribute (ecl).

Code: PHP (plus WordPress)Gizmo: QR Code Image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
add_shortcode('gizmo_qr_code_image', 'gizmo_qr_code_image_shortcode_handler');
 
function gizmo_qr_code_image_shortcode_handler($atts)
{
    // color MUST be a hex value (not an HTML color word)
 
    $parms = shortcode_atts(array(
        'size' => '100',
        'color' => '',
        'ecl' => 'L|4',
        'url' => '',),
        $atts);
 
    $size = $parms['size'];
    $color = $parms['color'];
    $ecl = $parms['ecl'];
    $url = $parms['url'];
 
    return gizmo_qr_code_image_func($size, $color, $ecl, $url);
}

The default attribute value for the size is 100 pixels; the coded images are always square. The default color value is an empty string; this means use the standard black color.

The error correction level defaults to L|4. Refer to the Google API documentation to explore the various permutations available.

Finally, the url is set to an empty string by default. This means use the url of the current web page.

Now … the workhorse function called by the shortcode handler:

Code: PHP (plus WordPress)Function: gizmo_qr_code_image_func

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function gizmo_qr_code_image_func($size=100, $color='', $ecl='L|4', $url='')
{
    // $ecl reference: http://code.google.com/apis/chart/docs/gallery/qr_codes.html#details
 
    $this_url = $url;
    if ($this_url == '')
    {
        // get the current url
        $this_url = 'http';
        if ($_SERVER["HTTPS"] == "on") {$this_url .= "s";}
        $this_url .= "://";
        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $this_url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        }
        else
        {
            $this_url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
    }
 
    // construct the image url
    $img_url = 'http://chart.apis.google.com/chart?cht=qr&chld=' . $ecl . '&chs=' . $size . 'x' . $size . '&chl=';
    $img_url .= $this_url;
 
    // change the color, if requested
    if ((strlen($color) == '6') || (strlen($color) == '7'))
    {
        // init images
        $src = imageCreateFromPng($img_url);
        $w = imageSX($src);
        $h = imageSY($src);
        $dest = imageCreateTrueColor($w, $h);
 
        // strip off # in hex color and get rgb array of values
        $new_color = $color;
        if (strlen($new_color) == 7)
        {
            $new_color = substr($new_color, -6, 6);
        }
        $new_color_array = wcs_gr_rgb_to_array(hexdec($new_color));
 
        // scan src image pixels and set dest image pixels
        for ($x = 0; $x < $w; $x++)
        {
            for ($y = 0; $y < $h; $y++)
            {
                $src_pix = imageColorAt($src, $x, $y);
                $src_pix_array = wcs_gr_rgb_to_array($src_pix);
 
                // image returned by google has black pixels set (0,0,0)
                if ($src_pix_array[0] == 0 && $src_pix_array[1] == 0 && $src_pix_array[2] == 0)
                {
                    $src_pix_array[0] = $new_color_array[0];
                    $src_pix_array[1] = $new_color_array[1];
                    $src_pix_array[2] = $new_color_array[2];
                }
                imageSetPixel($dest, $x, $y, imageColorAllocate($dest, $src_pix_array[0], $src_pix_array[1], $src_pix_array[2]));
            }
        }
 
        // start output buffering
        ob_start();
        imagePng($dest);
        $contents =  ob_get_contents();
        ob_end_clean();
        // complete image processing
        $img_url = 'data:image/png;base64,' . base64_encode($contents);
        imageDestroy($src);
        imageDestroy($dest);
    }
 
    // construct output HTML
    $output = '<img src="' . $img_url . '" width="' . $size . '" height="' . $size . '" />';
 
    // exit
    return $output;
 
    /**********************************************************************
     Copyright © 2011 Gizmo Digital Fusion (http://wpCodeSnippets.info)
     you can redistribute and/or modify this code under the terms of the
     GNU GPL v2: http://www.gnu.org/licenses/gpl-2.0.html
    **********************************************************************/
}
 
 
function wcs_gr_rgb_to_array($rgb)
{
    $a_colors[0] = ($rgb >> 16) & 0xFF;
    $a_colors[1] = ($rgb >> 8) & 0xFF;
    $a_colors[2] = $rgb & 0xFF;
    return $a_colors;
}

In lines 5-20, we get the current page/post's URL if one is not provided. This is standard PHP code to obtain this information. In lines 22-24, we setup Google's chart API function to retrieve the source image.

The heavy-duty work is performed by our color changer (lines 26-70), if applicable. First, we create a new image and then set its pixels based on the original incorporating color changes as needed. This is accomplished one pixel at a time. But because we're working with a small image resolution, the process is quick.

This portion of the code calls another function, wcs_gr_rgb_to_array(). This one converts an RGB color into three hue array components for use by the PHP image processing functions.

Next, we create a buffer to simulate writing the new image to a file. Otherwise, we'd need a separate PHP file to create the image on the fly.

Finally, we construct the output HTML and we're done. You may want to study this source code further. It offers a number of tricks that you might find useful elsewhere.

Share This Article: “How To Add QR Codes To Your Blog”

(Also Available: Press CTRL+D to Bookmark this Page)

Comments

Share Your Thoughts  7 Responses to “How To Add QR Codes To Your Blog”
  1. 1
    Ida says:

    I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. And, your code is very useful.

  2. 2
    Mia says:

    Now, i can put these qr codes on my blog, and know how it’s done. Thanks.

  3. 3
    anon says:

    Aftr I installed your qr code plugin, it was good to find the source code explained in detail.

  4. 4
  5. 5
    Steve says:

    Is there an easy way to call a php function so I can add this code to my template in WordPress?

Trackbacks

Check out what others are saying about this post...
  1. [...] QR Code GeneratorHow to Build an ‘Archives by Date’ …Plugin Review: WP-PageNaviHow To Add QR Codes To Your BlogHow To Fix the 3.1 Custom Permalinks BugUpgrading Older ThemesHow To Expand Your Blog’s [...]

  2. [...] This is truly the type of plugin that needs to be shared with other WordPress bloggers.  Ida: I’m truly enjoying the design and layout of your site. It’s a very easy on the eyes [...]



Share Your Thoughts

(Some editor features are restricted unless you're logged in.)

(When replying to a specific comment, your browser may require Shift+Enter instead of just Enter.)


(get a gravatar)


Notify me of followup comments via e-mail. You can also subscribe without commenting.