QRcode*
QRcode_encodeString(
    const char* string,
    int        version,
    QRecLevel    level,
    QRencodeMode  hint,
    int  casesensitive
)
1.0、参考
1.1、此函数的作用

将字符串编码到二维码中。

1.2、参数说明

const char* string是要编码的字符串。

int version表示生成的二维码的相对尺寸。取值范围为[4 ~ 40]。传入0就相当于4

QRecLevel表示容错等级,其定义如下:

typedef enum {
    QR_ECLEVEL_L = 0, // lowest
    QR_ECLEVEL_M,
    QR_ECLEVEL_Q,
    QR_ECLEVEL_H      // highest
} QRecLevel;

QRencodeMode表示提示信息,其定义如下:

typedef enum {
    QR_MODE_NUL = -1,   // Terminator (NUL character). Internal use only
    QR_MODE_NUM = 0,    // Numeric mode
    QR_MODE_AN,         // Alphabet-numeric mode
    QR_MODE_8,          // 8-bit data mode
    QR_MODE_KANJI,      // Kanji (shift-jis) mode
    QR_MODE_STRUCTURE,  // Internal use only
    QR_MODE_ECI,        // ECI mode
    QR_MODE_FNC1FIRST,  // FNC1, first position
    QR_MODE_FNC1SECOND, // FNC1, second position
} QRencodeMode;

int casesensitive表示英文字母是否大小写敏感。1:true 0:false

1.3、返回值说明

QRcode表示编码后的数据,其定义如下:

typedef struct {
    int version;         // version of the symbol
    int width;           // width of the symbol
    unsigned char *data; // symbol data
} QRcode;

int width表示点阵在水平方向上的点的个数。因为二维码是正方形的,所以,在竖直方向上点的个数与水平方向一样。

unsigned char *data表示点阵的数据,1表示黑色0表示白色

运行成功时,返回值不为NULL

运行失败时,返回值为NULL。并设置了errno变量的值,其值可能有如下:

error说明
EINVALinvalid input object.
ENOMEMunable to allocate memory for input objects.
ERANGEinput data is too large.
1.4、使用示例

step1、编写一个C语言源程序qrencodeTest.c,其内容如下

#include <qrencode.h>
#include <stdio.h>

int main(int argc, char* argv[]) {
    if (1 == argc) {
        printf("please provide a string to encode.\n");
        return 1;
    }

    QRcode* qrcode = QRcode_encodeString(argv[1], 1, QR_ECLEVEL_H, QR_MODE_8, 1);
    
    if (!qrcode) {
        extern int errno;
        printf("error occurred. code is %d\n", errno);
        return errno;
    }
    
    int i, j, width = qrcode->width;
    for (i = 0; i < width; i++) {
        for (j = 0; j < width; j++) { 
            if (qrcode->data[(i * width) + j] & 0x1) {
                printf("\033[40m  \033[0m");
            } else {
                printf("\033[47m  \033[0m");
            }
        }
        printf("\n");
    }
    
    QRcode_free(qrcode);

    return 0;
}

注意:这里仅仅是为了简单展示该函数的用法,所以将它用空白字符黑色背景白色背景表示点阵的10, 实际使用中,你可能要结合PNGBMP等编码技术,编码成相应的图片。

step2、使用cc命令进行编译

cc -o qrencodeTest -lqrencode qrencodeTest.c

step3、运行qrencodeTest

./qrencodeTest http://blog.fpliu.com/it

得到如下输出:

使用微信 → 扫一扫,即可解码成功。

source code on GitHub