使用 Google API 生成二维码

Jonty
2013-11-20 / 0 评论 / 59 阅读 / 正在检测是否收录...

Google API 可以非常方便的调用,下边的链接是一个示例:
[btnheart href="http://chart.apis.google.com/chart?cht=qr&chs=150x150&chld=L|2&chl=https://nobb.cc" target="_blank"]我是示例[/btnheart]

参数解释:

1、http://chart.apis.google.com/chart? 调用Google API
2、cht=qr 选择生成类型为 qr 码。
3、chs=150×150 设置二维码图片大小。
4、chld=L|4 L表示默认纠错水平;4表示二维码图片的留白大小,留白的大小也是计算在二维码图片大小内的,可选值为 1~4 的整数。
5、chl=https://nobb.cc为二维码内容。
一般 WordPress 文章页可以使用下边的代码调用二维码,具体自己调节参数。

<img src="http://chart.apis.google.com/chart?cht=qr&amp;chs=150x150&amp;chld=L|2&amp;chl=<?php the_permalink(); ?>" class="qrcode pic" width="150" height="150" alt="qrcode" />

由于 Google 服务器对国内不太稳定,所以我们可以把二维码图片缓存到本地来解决这一缺陷。

首先将下边的代码扔到当前主题的 functions.php 的最后一个 ?> 前。

/*
  *Bing - function - 二维码配置
  *Form:www.bgbk.org
*/

//二维码缓存
function Bing_qr($url,$path,$qrpic){
    set_time_limit (10);
    $destination_folder = $path?$path.'/':''; 
    $localname = $destination_folder .$qrpic;     
    $file = fopen ($url, "rb");
    if($file){
      $newf = fopen ($localname, "wb");
        if($newf)     
            while(!feof($file)){     
                fwrite( $newf, fread($file, 1024 * 2 ), 1024 * 2 );
            }     
        }     
    if($file){     
        fclose($file);
    }     
    if($newf){     
        fclose($newf);    
    }
}

//生成二维码地址
function Bing_echo_qr($imgsize = 150,$echo = true){
    $cache = false;
    $cache = true;
    if(is_single() || is_page()) $imgname = get_the_id();
    elseif (is_home() || is_front_page())  $imgname = 'home';
    elseif(is_category()) $imgname = 'cat-'.get_query_var('cat');
    elseif(is_tag()) $imgname = 'tag-'.get_query_var('tag_id');
    if(!is_home()) $permalink = get_permalink();
    else $permalink = get_option('home');
    if($cache){
        $localqr =  ABSPATH .'qrcode/'.$imgname.'.jpg';
        if(!file_exists($localqr)){
            Bing_qr("http://chart.googleapis.com/chart?cht=qr&amp;chs=".$imgsize."x".$imgsize."&amp;choe=UTF-8&amp;chld=L|0&amp;chl=".$permalink ,"qrcode", $imgname.".jpg");
        }
        $main = get_home_url('').'/qrcode/'.$imgname.'.jpg';
      }
      else $main = "http://chart.googleapis.com/chart?cht=qr&amp;chs=".$imgsize."x".$imgsize."&amp;choe=UTF-8&amp;chld=L|0&amp;chl=".$permalink;
      if($echo) echo $main;
      else return $main;
}

//输出二维码
function Bing_echo_qrcode($imgsize = 150){
    echo '<img src="'.Bing_echo_qr($imgsize,false).'" class="qrcode" width="'.$imgsize.'" height="'.$imgsize.'" alt="qrcode" />';
}

然后在需要调用二维码的地方使用下边的函数就行了:

<?php if(function_exists('Bing_echo_qrcode')&amp;&amp;function_exists('Bing_echo_qr')&amp;&amp;function_exists('Bing_qr')) Bing_echo_qrcode(150);?>

其中的 150 为二维码大小,可以自己修改。

如果想关闭二维码缓存只需要将第一段代码的 30 行 $cache = true; 注释掉即可。

本文共 268 个字数,平均阅读时长 ≈ 1分钟
0

打赏

海报

正在生成.....

评论 (0)

取消