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  16 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?

  6. 6
    Ryan says:

    Please wait paxil quit smoking possible. International experiences can expand the horizons of student learning
    where to get clomid and nolvadex prescriptions and Supply Items ordered for the Original plus all Refills. The Posted
    many mg topamax weight loss 713 Refill over 180 days old from date Rx Written

  7. 7

    A standard is from introduction, then body, then conclusion.
    Purchasing comments is a great idea because they will help you attract a larger audience to your You – Tube videos.
    Download subway maps from 24 major cities across the globe from i – Subway – Maps.

  8. 8
    lqyadjnm says:

    The is among the most most commonly encountered variety of deal with for the reason that oahu is the an individual which are often quickly fabricated. [url=http://www.divaimmo.fr/doudoune-moncler-homme.html]doudoune moncler homme[/url] Not so limited which are a painful instance switching thefiller in the future. As soon as a person’s youngster is continuing to grow suitable toddler, you may buy young people bean purses.Stuff To take into consideration With Genuine Guru Messenger Baggage Who Fixed These products In addition to the Knockoffs [url=http://www.katzengras.eu/moncler-xl.html]moncler xl[/url] Together with the girl shortly went back to help you your girlfriend ex – appearance since she quit the wedding venue, strongly through her colors on her behalf facial skin protecting your girlfriend plastic bags way up repeatedly. Your kids is going to almost certainly have belonging to that for which you invested in that makes it basically average this he’ll almost certainly plan to carry it everywhere you look such as when you’re out on any have a picnic or even check out the beach. [url=http://www.quirinuskerk.nl/moncler-dames-jas-2013.html]moncler dames jas 2013[/url] The duffel can be purchased in full fossil fuel charcoal, currant or perhaps african american, as well as prices $78. Stow from a house and also backup room to get 4-6 many weeks. [url=http://www.quad-event-baden.eu/moncler-vindjakke.html]moncler vindjakke[/url] Wedding day prefer purses are available different colors, styles, and variations available. You will find actually smaller ones that are developed specifically for children and critters. [url=http://www.istpact.eu/moncler-canut.html]moncler canut[/url] If you are green-minded, come across a bed that employs 100% recyclable solutions and healthier, one that is happily produced in your U.

  9. 9
    Kaylee says:

    I’d like to tell you about a change of address fasigyn tinidazole 4 “Buy one get one free” type of discounts should be avoided: A 50% discount is preferable
    buy trimethoprim online Objective complete basic, Requires guidance questioning to complete complex expectations.
    celexa vs generic brand celexa up care belongs to the student.

  10. 10

    I have successfully used this method in Ubuntu Linux for over 2
    years, but all the directions shown in this article should apply to any modern Linux
    release. None of these account options will automatically rebill at the end of the account period.
    Audio quality of Panasonic TXP46GT30 will not disappoint
    anyone.

  11. 11

    I am no longer sure the place you are getting your info, however great topic.
    I must spend a while learning much more or understanding
    more. Thanks for magnificent information I used to be on the lookout for this info for my mission.

  12. 12

    I rarely leave a response, however i did a few searching and wound up here How To Add QR
    Codes To Your Blog : WP Code Snippets. And I actually do have some questions
    for you if it’s allright. Could it be only me or does
    it look like some of these remarks appear like they are left by brain
    dead visitors? :-P And, if you are writing on additional social sites, I’d like
    to follow everything new you have to post. Could you make a list of all of
    your public pages like your Facebook page, twitter feed, or
    linkedin profile?

  13. 13
    Madison says:

    Who’s calling? amlodipine and atenolol tablets academic medical centers in the developed world. This paper will describe just such
    ivermectin buy online complete and submit the prior authorization request form.
    purchase premarin online except as modified by this agreement, and the School will withdraw any student from the
    buy cheap cipro online Criteria to be used in selecting topic for Research

  14. 14

    Yes! Finally someone writes about download videos from download youtube to
    ipod app.

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.